Wednesday, January 9, 2013

Quadratic sorting algorithm

Bubble sort:
Time complexity: O(n^2)
Can be used to detect whether an array is sorted.

Selection sort:
Time complexity: O(n^2)

Insertion sort:
Time complexity: O(n^2)
Very efficient on almost sorted array.
In practice, it is more efficient than other simple quadratic sorting algorithms such as selection sort and bubble sort.

Here are the source code for the sorting algorithms above.


void mySort::myBubbleSort(int *Q, int begin, int end){
bool isSorted=0;
int temp;
while(!isSorted){
isSorted=1;
for(int i=0; i<end; i++){
if(Q[i]>Q[i+1]){
temp=Q[i];
Q[i]=Q[i+1];
Q[i+1]=temp;
isSorted=0;
}
}
}
}

myMin mySort::myFindMin(int *Q, int begin, int end){
myMin minValue;
minValue.value=Q[begin];
minValue.pos=begin;
for(int i=begin; i<=end; i++){
if(Q[i]<minValue.value){
minValue.value=Q[i];
minValue.pos=i;
}
}
return minValue;
}
void mySort::mySelectionSort(int *Q, int begin, int end){
myMin minValue;
int temp;
for(int i=0; i<end;i++){
minValue=myFindMin(Q,i,end);
//cout<<"The minimum element is:"<<minValue.value<<" @ "<<minValue.pos<<endl;
temp=Q[i];
Q[i]=Q[minValue.pos];
Q[minValue.pos]=temp;
}
}

void mySort::myInsertionSort(int *Q, int begin, int end){
int temp;
int j;
for(int i=1; i<=end; i++){
temp=Q[i];
for(j=i-1; j>=0;j--){
if(Q[j]>temp)
 Q[j+1]=Q[j];
else{
break;
}
}
Q[j+1]=temp;
}
}

No comments:

Post a Comment