selection sort

/***
selection sort: O(n2)
find the min on the right part and exchange
***/

#include<iostream>

using namespace std;

class selectionSort {
public:
       selectionSort(int *a, int sz);
       ~selectionSort() { }
       void sort();
       void print();
private:
       int *as;
       int size;
       void exchange(int *a1, int *b1);
       int getmin(int begin, int end);
};

selectionSort::selectionSort(int *a, int sz):as(a), size(sz) { }

void selectionSort::sort() {
       int pos;
       for(int i = 0; i < size; i++) {
              pos = getmin(i, size-1);
              exchange(as+i, as+pos);
       }
}

int selectionSort::getmin(int begin, int end) {
       int min = as[begin], pos = begin;
       for(int i = begin; i <= end; i++) {
              if(min > as[i]) {
                     min = as[i];
                     pos = i;
              }
       }
       return pos;
}

void selectionSort::exchange(int *a1, int *b1) {
       int temp;
       temp = *a1;
       *a1 = *b1;
       *b1 = temp;
}

void selectionSort::print() {
       for(int i = 0; i < size; i++) {
              cout<<as[i]<<" ";
       }
       cout << endl;
}

void main() {
       int a[] = {3, 1, 4, 5, 2, 8, 6};
       int size = sizeof(a) / sizeof(int);
       selectionSort st(a, size);
       st.sort();
       st.print();

}

Comments

Popular posts from this blog

Unique Binary Search Trees

Coin in Line