4.SelectionSort - C++

less than 1 minute read

4.SelectionSort - C++




#include <iostream>


//void printArr (int arr[],int size){
//    int i;
//    for (i=0; i<size; i++){
//        std::cout <<  arr[i] << ", ";
//    }
//    std::cout << "\n";
//}

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

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


int main(int argc, const char * argv[]) {
    int arr[] = { 3,2,3,1,5,6,7,8,9,10 };
    int size = sizeof(arr)/sizeof(int);
    
//    printArr(arr, size);
//    selectionSort(arr, size);
//    printArr(arr, size);
    
    selectionSort(arr, size);
    for(int x:arr) std::cout << x << " ";
    
}






Leave a comment