void selection_sort (int *a, int n) {
    int i, j, m, t;
    for (i = 0; i < n; i++) {
        for (j = i, m = i; j < n; j++) {
            if (a[j] < a[m])
                m = j;
        }
        t = a[i];
        a[i] = a[m];
        a[m] = t;
    }
}

int main () {
    int a[] = {4, 65, 2, -31, 0, 99, 2, 83, 782, 1};
    int n = sizeof a / sizeof a[0];
    selection_sort(a, n);
    return 0;
}

hi, can u pls help me understand this code line by line..
i understand how selection sort works.
but not able to get this code properly.
just anyone pls explain me the wrking of this code( selection sort function)

Recommended Answers

All 3 Replies

// Selection sort.
//  'a' : A pointer to the first entry of the array of numbers to sort.
//  'n' : The number of entries in the array.
void selection_sort (int *a, int n) {
    int i, j, m, t;
    // For all positions 'i' in the array,
    for (i = 0; i < n; i++) {
        // find the position 'm' of the minimum value in the range 'i' to 'n' 
        for (j = i, m = i; j < n; j++) {
            // if the 'j' entry is lower than the current minimum 'm',
            if (a[j] < a[m])
                m = j;  // then mark 'j' as the current minimum 'm'.
        }
        // Swap the minimum entry with entry 'i', and move on to the next entry.
        t = a[i];
        a[i] = a[m];
        a[m] = t;
    }
}

I don't know what else to explain, there really isn't much to explain. Is there a specific thing that troubles you?

The outer for loop in line 3 can be thought of as the counter for the progress of the sorted part of your list/array.

The inner for loop in line 4 is a loop that traverses the unsorted part of the list. Remember that the outer for loop at line 3 keeps track of the sorted part of the list(and therefore the unsorted part as well), so we get the value of i which is the index of the unsorted part of the list and then traverse it trying to find the smallest number via the if at line 5 where variable j is the 'traversing' variable and m is the index that will hold the index that contains the smallest integer. If we find a number that is smaller than the one we currently have, we run m = j, so naturally we will eventually have the index of the smallest number in the unsorted list. We assume that the first index in the unsorted list is the smallest number, just to have somewhere to start from so we assign m = i.

Line 8 to 10 is the part where the switching happens. After that, the i variable of the outer loop advances, and therefore our sorted part of the list also advances.

understood it very well.. thanks for the help.... :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.