Quick actions

cmd+k|ctrl+k

Navigation

Languages

Selection Sort in c++

Snippet info

Language

Cpp

Visibility

public

Author

umashankar

Created

2021-04-28T17:56:38.411049Z

Updated

2021-04-28T19:19:01.248576Z

/*
    Impletementation of Selection Sort using c++
    how Selection sort works
    in ASC
    step1 - take the current element as minumum
    step2 - move through the next elements in the list or array
    step3 - if any element in the index is greater than minumum element swap
    step4 - repeat the above three steps
    Time complexity - 
*/
#include <iostream>
using namespace std;

//Function Declarations
void selectionSort(int* arr, int n);
void inputArray(int* arr, int n);

int main() {
    cout << "How many elements do you wanna enter: ";
    int n;
    cin >> n;
    int *arr = new int(n);
    // size_t n = sizeof(arr)/sizeof(arr[0]);
    // int *array{ new int[5]{ 10, 7, 15, 3, 11 } };
    cout << "Enter Elements into the Array:\n";
    inputArray(arr,n);
    selectionSort(arr, n);
    cout << "\nAfter Sorting: ";
    for(int i =0; i<n; ++i){
        cout << arr[i] << "\t";
    }
    delete []arr;
    return 0;
}

void inputArray(int* arr, int n){
    for(int i=0; i<n; ++i){
        cout << "Enter the Element: ";
        cin >> arr[i];
        cout << "\n";
    }
    return;
}


void swap(int* a, int* b){
    int temp = *a;
    *a = *b;
    *b = temp;
    return;
}

void selectionSort(int* arr, int n){
    int min_index;
    for(int i=0; i<n; ++i){
        min_index = i;
        for(int j= i+1; j<n; ++j){
            if(arr[j] < arr[min_index]){
                min_index = j;
            }
        }
        swap(arr[min_index], arr[i]);
    }
    return;
}

// Since we use two loops inside the function the Time Complexity is O(n^2)

INFO