快速排序,选择排序

来源:互联网 发布:yii框架源码分析 编辑:程序博客网 时间:2024/05/17 07:29

选择排序

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
int selectionSort(int argv[], int size) // 选择排序
{
int time = 0; // 计算比较次数
for (int i = 0; i < size; i++)
{
int minIndex = i;
for (int j = i+1; j < size; j++)
{
++time;
if (argv[j] < argv[minIndex])
{
minIndex = j;
}
}
if (minIndex != i)
{
int temp = argv[i];
argv[i] = argv[minIndex];
argv[minIndex] = temp;
}
}
return time;
}
 来自CODE的代码片
selectionSort.cpp

快速排序

  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
int QuickSort(int argv[], int low, int high)
{
static int time = 0; // 计算调用次数
++time;
if(low>=high) // 比较到中间结束
return time;
int l = low;
int h = high;
int k = argv[low]; // 以数组开头做为k,
while(l != h) // 作用把小于k的数放在k左边,大于k的数放在k的右边。
{
while(l < h && argv[h] >= k) // 从后high开始往前找到第一个小于k的下标记做h
{
h--;
}
argv[l] = argv[h]; // 把小的数放l的位置。argv[h]相当于变为空位(数据已经移走,但没有清除)
while(l<h && argv[l]<= k) // 从l开始往后找到第一个大于k的下标记做l
{
l++;
}
argv[h]=argv[l]; // 把找到的大数放到argv[h]和空位中,argv[l]相当于变为空位(数据已经移走,但没有清除)。
}
argv[l]=k; // 把k空位argv[l]中。此时完成了把k放入最终的位置并把小于k的数放在k左边,大于k的数放在k的右边。
QuickSort(argv, low, l-1); // 此时l位置的数为从low到l之间的最大数
QuickSort(argv, l+1 ,high); // 此时l位置的数为从l到ligh之间的最小数
return time;
}
 来自CODE的代码片
原创粉丝点击