Friday, June 7

Exchange Sort using Java

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");
        }
    }
}


OUTPUT

~~~~~~~

Please Enter how many numbers to be sorted :     8

Enter the numbers

50
62
1
9
2
100
60
55

Sorted Elements are :
1  2  9  50  55  60  62  100

No comments:

Post a Comment

Backup files to google drive using PHP coding

 Dear All, To backup files to Google Drive using PHP coding, you can use the Google Drive API and the Google Client Library for PHP. Here...