Hi All,
Here I write a program for Exchange Sort Using Java.
The exchange sort compares each element of an array and swap those elements that are not in their proper position, just like a bubble sort does. The only difference between the two sorting algorithms is the manner in which they compare the elements.
public class exchangeSort {
public static void main(String args[]) {
int n, i, j, temp;
Scanner in = new Scanner(System.in);
System.out.print("Please Enter how many numbers to be sorted : \t");
n = in.nextInt();
System.out.println("Enter the numbers\n");
int num[] = new int[n];
for (i = 0; i < n; i++) {
num[i] = in.nextInt();
}
for (i = 0; i < num.length - 1; i++) {
for (j = i + 1; j < num.length; j++) {
if (num[ i] > num[ j]) //sorting into Ascending order /* if you want descending order (num[ i] < num[ j]) */
{
temp = num[ i]; //swapping
num[ i] = num[ j];
num[ j] = temp;
}
}
}
try {
for (int k = 0; k < num.length; k++) {
System.out.print(num[k] + "|");
}
System.out.println();
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Exception");
}
}
}
No comments:
Post a Comment