I previously tested the same variable called "swaps" for bubble sort algorithm and it worked perfectly. Now, with selection sorting, variable loses its value even after incrementing it. Any help will be very much appreciated.
int list[] = {10, 5, 6, 3, 4, 11, 9, 7, 2};
int min = list[0], pos = 0, temp_max = 0;
// Loop until no swap is needed
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
int swaps = 0,
// Iterate through array to find min value
for (int i = j, y = sizeof(list) / sizeof(int); i < y; i++)
{
if (list[i] < min)
{
min = list[i];
pos = i;
}
}
// Insert min value in left most position and add 1 to swaps, meaning array is not yet sorted
if (pos > j)
{
temp_max = list[j];
list[j] = min;
list[pos] = temp_max;
swaps++;
}
// The error might occur here: "swaps" keeping value 0 after previous if statement ends
printf ("swaps = %d\n", swaps);
// If no swaps ocurred, array is sorted
if (swaps == 0)
{
// Print sorted array and return
}
}
Adding to the other answers, which will fix the problem specifically with your code, you can also approach the selection sort algorithm like this.
Steps to writing this algorithm for an array:
1. Write a helper function to find the index of the biggest element in the array:
2. Iterate over
i=n
toi=1
, and find the biggest value betweenlist[0]
andlist[i-1]
. After this element is found, swap it into the last position. The function could look like this:3. Considering these ideas, you can write a simple version of the algorithm like this:
Output:
Compiled with: