Header Ads

Header ADS

program to implement selection sort


 #include <iostream>

using namespace std;


int main() {

    int i, j, n, loc, temp, min, a[30];

    cout << "enter the number of elements: ";

    cin >> n;

    cout << "\nenter the elements:\n";


    // Use < instead of = in the for loop condition

    for (i = 0; i < n; i++) {

        cin >> a[i];

    }


    for (i = 0; i < n - 1; i++) { // Change n=1 to n-1

        min = a[i];

        loc = i;

        for (j = i + 1; j < n; j++) { // Change n to n-1

            if (min > a[j]) {

                min = a[j];

                loc = j;

            }

        }

        temp = a[i];

        a[i] = a[loc];

        a[loc] = temp;

    }


    cout << "\nsorted list is as follows:\n";

    for (i = 0; i < n; i++) {

        cout << a[i] << " ";

    }

    return 0;

}


No comments

Powered by Blogger.