import java.util.Scanner;
public class sortNumber {
public static void main(String[] args){
int []intNum = new int[5];
Scanner sc = new Scanner(System.in);
/* Get Number from USER 5 numbers */
for(int i = 0 ; i<5 ; i++){
System.out.print("Enter number"+(i+1)+" :");
intNum[i] = sc.nextInt();
}
/* Sort elements by Bubble Algorithm */
/* index 0 1 2 3 4
intNum :8 9 3 2 7 : 8<9 T -> 8<->9
1 -> 8<9 T -> 8<=>9
-> 9 8<3 F
-> 9 8 3<2 F
-> 9 8 3 2<7 T -> 2<=>7 [4 steps]
-> 9 8 3 7 2 : end round 1st
2 -> 9<8 F
-> 9 8<3 F
-> 9 8 3<7 T -> 3<=>7 [3 steps]
-> 9 8 7 3 2 ; end round 2nd
3 -> 9<8 F
-> 9 8<7 F [2 steps]
-> 9 8 7 3 2 ; end round 3rd
4 -> 9<8 F [1 steps]
-> 9 8 7 3 2 : end round 4rd
*/
int temp; /* swap number */
for(int j=4 ; j>0 ; j--){
for(int i=0 ; i<j ; i++)
if(intNum[i]<intNum[i+1]){
temp = intNum[i];
intNum[i] = intNum[i+1];
intNum[i+1] = temp;
}
}
/* Show the sorted number */
for(int i = 0 ; i<5 ; i++){
System.out.println("Enter number"+(i+1)+" :"+intNum[i]);
}
}
}
www.ibooksharing.com www.csBook-jack.blogspot.com * programming in C++ , C , Java , HTML , Objective-C , Unix , Javascript , Xcode , iOS , Development , Computer Science and More *
Tuesday, February 14, 2012
Java - Bubble sort [ example code ]
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment