mercredi 28 juin 2017

Why is the Insertion sort giving ans in descending order when it is suppose to output in ascending order?

Insertion sort. Where you find the smallest number in the array and compare with arr[i] (arr(0) at initial), if the counter number is smaller than the initial then they swap their positions. And the for loop goes on till array finishes. The full code is below:

#include <iostream>

using namespace std;

int main()
{
    int arr[] = {11,55,2,4,5,2,48,854,5,2,4,7,8,2,41,4,8,5,2,18};
    int x = sizeof(arr) / sizeof(arr[0]);
    int small, temp;

    for(int i = 0; i != x; i++) {
        small = i;

        for(int j = 0; j != x; j++) {
            if(arr[small] > arr[j]) {
                small = j;

                if(small != i) {
                    temp = arr[i];
                    arr[i] = arr[j];
                    arr[j] = temp;
                }
            }
        }
    }

    for(int num: arr) {
        cout << num << " , ";
    }
    return 0;
}

The problem is on line where "arr[small] > arr[j]" means if variable at index j is smaller than initial (arr[small]) then they swap places, thus the ans should have been in ascending order but the output is opposite, it comes as descending order and vice versa.

for(int j = 0; j != x; j++) {
            if(arr[small] > arr[j]) { // the output is [854....2]
                small = j;

                if(small != i) {

I am an amateur programmer, thus, I have no other way than to seek for our help.

Thank you.

Aucun commentaire:

Enregistrer un commentaire