1、Bubbling sort
#include <iostream>
#include <ctime>
using namespace std;
void bubbleSort(int iarray[], int n)
{
bool flag = false;
for(int i=0; i<n-1&&!flag; ++i)
{
for(int j=i+1; j<n; ++j)
{
if(iarray[i]>iarray[j])
{
int tmp = iarray[i];
iarray[i] = iarray[j];
iarray[j] = tmp;
}
}
}
}
int main()
{
int iarray[10];
srand(time(NULL));
for(int i=0; i<10; ++i)
{
iarray[i] = rand()%100;
cout << iarray[i] << " ";
}
cout << endl;
bubbleSort(iarray, 10);
for(int i=0; i<10; ++i)
{
cout << iarray[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
2、quick sort
#include <iostream>
#include <ctime>
using namespace std;
const int ARRAY_LEN = 100;
int iarray[ARRAY_LEN];
int divide(int low, int high)
{
if(low>=high)return -1;
int pvoit = iarray[low];
while (low<high)
{
while (iarray[high]>=pvoit&&low<high)
{
high--;
}
if(low<high)
{
iarray[low] = iarray[high];
low++;
}
while (iarray[low]<=pvoit&&low<high)
{
low++;
}
if(low<high)
{
iarray[high] = iarray[low];
high--;
}
}
iarray[low] = pvoit;
return low;
}
void myQsort(int low, int high)
{
int mid = divide(low, high);
if(mid!=-1)
{
myQsort(low, mid-1);
myQsort(mid+1, high);
}
}
int main()
{
srand(time(NULL));
for(int i=0; i<20; ++i)
{
iarray[i] = rand()%100;
cout << iarray[i] << " ";
}
cout << endl;
myQsort(0, 19);
for(int i=0; i<20; ++i)
{
cout << iarray[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
3、HeapSort
//第一步:建立大顶堆,从最后一个非叶子节点按照从右到左从下到上的顺序逐步调整当前子树为大顶堆直到根节点
//第二步:移除大顶推的顶