//排序算法,从小到大
#include <iostream>
using namespace std;
void swap(int &a, int &b)
{
int temp;
temp = a;
a = b;
b = temp;
}
//选择排序
void selectSort(int array[],int len)
{
cout << "selectSort:";
for (int i = 0; i < len; i++)
{
for (int j = i+1; j < len; j++)
{
if (array[i]>array[j])
{
swap(array[i], array[j]);
}
}
cout << array[i] << " ";
}
cout << endl;
}
//冒泡排序
void bubbleSort(int array[], int len)
{
cout <<"bubbleSort:";
for (int i = 0; i < len; i++)
{
for (int j =len-1; j >i; j--)
{
if (array[i]>array[j])
{
swap(array[i], array[j]);
}
}
cout << array[i] << " ";
}
cout << endl;
}
//插入排序
void insertSort(int array[], int len)
{
cout << "insertSort:";
int i = 0;
for (i = 0; i < len; i++)
{
int k = i;
int temp = array[k];
for (int j = k; j >=0; j--)
{
if (temp<array[j])
{
array[j+1]=array[j];
k = j;
}
}
array[k] = temp;
cout << array[i] << " ";
}
cout << endl;
}
//希尔排序
void shellSort(int array[], int len)
{
cout << "shellSort:";
int i = 0;
int gap = len;
for (i = gap; i < len&&gap>=1; i+=gap)
{
gap = gap / 3 + 1;
int k = i;
int temp = array[k];
for (int j = i-gap; j >= 0; j -= gap)
{
if (temp<array[j])
{
array[j + gap] = array[j];
k = j;
}
}
array[k] = temp;
}
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
//快速排序
int partition(int array[], int low, int high)
{
int pivot = array[low];
if (low < high)
{
while ((low < high) && (array[high] >= pivot))
{
high--;
}
swap(low,high);
while ((low < high) && (array[low] <pivot))
{
low++;
}
swap(low, high);
}
return low;
}
void quickSort(int array[], int low, int high)
{
if (low < high)
{
int pivot = partition(array, low, high);
partition(array, low, pivot - 1);
partition(array, pivot + 1, high);
}
}
void quickSort(int array[], int len)
{
quickSort(array, 0,len-1);
cout << "quickSort:";
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
int main()
{
int array[] = {8,7,55,69,2,58,4,37,46,24};
int len = 10;
cout << "原序列:";
for (int i = 0; i < len; i++)
{
cout << array[i] << " ";
}
cout << endl;
selectSort(array, len);
bubbleSort(array, len);
insertSort(array, len);
shellSort(array, len);
quickSort(array, len);
system("pause");
return 0;
}