您的位置:首页 > 其它

简单排序算法的汇总(快速排序、直插排序、希尔排序、选择排序、冒泡排序)

2016-12-06 19:42 281 查看
#include<string.h>
#include<stdio.h>
#include<iostream>
using namespace std;

#define MAX_LENGTH 10

//快速排序
void quickSort(int* a, int low, int high)
{
if (low >= high || NULL == a)
{
return;
}

int i = low;
int j = high;
int tempKey = a[i];

//一趟快排
if (i < j)
{
while(i < j)
{
//从后端找出第一个比key大的值,然后替换
while(i < j && tempKey <= a[j])
{
j--;
}

if(i < j && tempKey > a[j])
{
a[i] = a[j];
i++;
}

//从前端找到第一个key小的值,然后替换
while(i < j && tempKey >= a[i])
{
i++;
}

if(i < j && tempKey < a[i])
{
a[j] = a[i];
j--;
}
}

//tempKey回到分割点
if(i == j)
{
a[i] = tempKey;
}
}

//经过以上的循环,就可以把数组的分割
//比tempKey小的在左边,大的在右边
//然后通过递归,进行分割排序

if(low < i-1)
{
quickSort(a, low, i-1);
}

if(i+1 < high)
{
quickSort(a, i+1, high);
}
}

//插入排序
void insertSort(int a[], int length)
{
if(NULL == a || length <= 0)
{
return;
}

for (int i = 1; i < length; i++)
{
for (int j = i - 1; j >= 0 && a[j] > a[j + 1]; j -= 1)
{
swap(a[j], a[j + 1]);
}
}
}

//希尔排序的实质就是分组插入排序,该方法又称缩小增量排序
void shellSort(int a[], int length)
{
if(NULL == a || length <= 0)
{
return;
}

for (int gap = length / 2; gap > 0; gap /= 2)
{
for (int i = gap; i < length; i++)
{
for (int j = i - gap; j >= 0 && a[j] > a[j + gap]; j -= gap)
{
swap(a[j], a[j + gap]);
}
}
}
}

//选择排序
//已经排序的数据(整个数组的排序)-> i -> 未排序
void selectSort(int* a, int length)
{
if(NULL == a || length <= 0)
{
return;
}

for(int i = 0; i < length; i++)
{
//遍历值的下标(将会存储没排序数据的最小值)
int tempIndex = i;

bool bchange = false;

//未排序的数据中,找到最小的数值
for(int j = i + 1; j < length; j++)
{
if(a[tempIndex] > a[j])
{
tempIndex = j;
bchange = true;
}
}

//找到最小值,进行交换
if(bchange == true)
{
swap(a[i], a[tempIndex]);
}
}
}

//冒泡排序,单向排序
void bubbleSort(int* a, int length)
{
if(NULL == a || length <= 0)
{
return;
}

bool bchange = false;
for(int i = 0; i < length - 1; i++)
{
for(int j = length -1; j > i; j--)
{
if(a[j] < a[j-1])
{
swap(a[j], a[j-1]);
bchange = true;
}
}

if(!bchange)
{
return;
}
}
}

int main()
{
int a[MAX_LENGTH] = {30, 10, 29, 39, 18, 90, 0, 58, 29, 4};
int length = sizeof(a)/sizeof(int);
cout << "length=" << length <<endl;

//  quickSort(a, 0, length-1);
//  insertSort(a, length);
//  shellSort(a, length);
//  selectSort(a, length);
bubbleSort(a, length);

for(int i = 0; i < length && i < MAX_LENGTH; i++)
{
cout << a[i] << " ";
}

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐