0

I used printf to check the process and final result. The final result is technically correct (the array is sorted in ascending order) but I saw the behaivior of the algorithm and it doesnt look like selection. I could be wrong. Any thoughts? Thanks!


int arr[] = {88, 22, 342, 23, 501, 313, 90, 112, 125, 1, 3, 45};
int size = sizeof(arr) / sizeof(arr[0]);


for (int x = 0; x < size; x++){

for (int i = 0; i < size-1; i++){
   int holder;

   if (arr[i] > arr[x]){
       holder = arr[x];
       arr[x] = arr[i];
       arr[i] = holder;

   }

} 
}    
}
1
  • This is a bubblesort algorithm – MARS Apr 26 '17 at 19:48
0

Like @MARS pointed out, you currently have a bubble sort algorithm. In a bubble sort algorithm, you iterate over a list, compare adjacent elements, swap elements that are in the wrong order, and "bubble" the largest element to the end. The list is sorted once no elements have been swapped. I got this from the walkthrough.

So what is a selection sort algorithm? According to the walkthrough, the pseudocode for selection sort is:

for i = 0 to n - 1
    for j = i + 1 to n
        find index of minimum value
    swap array[min] and array[i]

Here is the pseudocode from the selection sort video (It's a little different as you'll see):

for i = 1 to n - 1
    min = i
    for j = i + 1 to n
        if array[j] < array[min]
            min = j
    if min != i
        swap array[min] and array[i]

If you still have issues, comment below. :-)

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .