Two sorting versions

I recently studied sorting algorithms and, like many other books that I started reading, it starts with implementing sorting. The code was as follows:

Implementation A

//a is an array of ints.
int n = a.length;
    for(int i = 0; i < n; i ++){
        int min =0;
        for( int x = i+1; x <n;x++){
            if(a[x].compareTo(a[i])<0){
                Comparable tmp = a[i];
                a[i] = a[x];
                a[x] = tmp;                 
            }
        }
    }

After analyzing the code, I changed the algorithm as follows.

Implementation B

//a is an array of ints
int n = a.length;
    for(int i = 0; i < n; i ++){
        int min =i;
        for( int x = i+1; x <n;x++){
            if(a[x].compareTo(a[min])<0){
                        min=x;      
            }
        }

        if(min>i){
            Comparable tmp = a[i];
            a[i] = a[min];
            a[min] = tmp;
        }

    }

I also found similar implementations on the Internet, using the min value to find the smallest value in the array, and then replacing it with an element at the i position of the array. My question is: Is there something wrong with the second implementation? is this not the right sort choice because it does not replace every element it finds that is smaller than the element at position i, but instead expects it to find the smallest element in the array before replacing?

10000 , , . .

0
1
0

Source: https://habr.com/ru/post/1672647/


All Articles