Search code examples
c++sortingselection-sortarray-algorithms

Applying selection sort on an array of integers


int arr[] = {7,4,10,8,3,1};
int size = sizeof(arr) / sizeof(arr[0]);

for(int i = 0; i<size-1; i++){
    
    int temp = arr[i];
    
    for(int j = i+1; j < size; j++){
        
        if(arr[j] < temp){
            temp = arr[j];
        }
        
    }
    
    swap(temp, arr[i]);
}

I am trying to apply the selection sort algorithm on the given array, but the output I am getting is only [1,1,1,1,1,1], I am finding the minimum element through the inner loop, Ican't figure out what is going wrong?


Solution

  • The first mistake you made in writing for loop's condition, don't use swap(temp, array[i]); yet try to get the basics first.

    #include <iostream>
    
    using namespace std;
    
    int findsmall(int arr[], int i, int size){
        int s, pos, j;
        s = arr[i];
        pos = i;
        for(j = i+1; j < size; j++){
            if(arr[j] < s){
                s = arr[j];
                pos = j;
            }
        }
        return pos;
    }
    
    int main() {
        
        int arr[] = {7,4,10,8,3,1};
        int size = sizeof(arr) / sizeof(arr[0]);
        int smallnum;
        int temp;
        int count = 0;
        
        cout << "Original array: ";
        
        for(int i = 0; i < size; i++){
            if(i < size - 1){
            cout << arr[i] << ", ";}
            else{
                cout << arr[i];
            }
        }
        
        cout << endl;
        
        for(int i = 0; i < size; i++){
            smallnum = findsmall(arr,i, size);
            temp = arr[i];
            arr[i] = arr[smallnum];
            arr[smallnum] = temp;
            count++;
        }
        
        
        
        cout << "Sorted array: ";
        
        for(int i = 0; i < size; i++){
            if(i < size - 1){
            cout << arr[i] << ", ";}
            else{
                cout << arr[i];
            }
        }
        
        cout << endl;
        
        return 0;
    }