1 选择排序
思想:从前到后依次确定每一个位置应该有的数(位置优先),选择的意思就是为每一个位置选择最合适的值。
#include <stdio.h>
int main()
{
int i = 0;
int j = 0;
int a[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
int len = 10;
int temp = 0;
for(i = 0; i < len - 1; i++)
{
for(j = i+1; j < len; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
for(i = 0; i < len; i++)
{
printf("%d ", a[i]);
}
}
2 插入排序
思想:对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入。
#include <stdio.h>
int main(int argc, const char *argv[])
{
int i = 0;
int j = 0;
int a[10] = {10,9,8,7,6,5,4,3,2,1};
int len = 10;
int temp = 0;
for(i = 1; i < len; i++)
{
j = i;
temp = a[i];
while(j > 0 && temp < a[j - 1])
{
a[j] = a[j - 1];
j--;
}
a[j] = temp;
}
for(i = 0; i < len;i++)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
3 冒泡排序
思想:每次小循环将未排序数字中的最大的以后放到后面。
#include <stdio.h>
int main(void)
{
int i = 0;
int j = 0;
int a[10] = {10,9,8,7,6,5,4,3,2,1};
int temp = 0;
int len = 10;
for(i = 0; i < len - 1; i++)
{
for(j = 0; j < len - 1 - i; j++)
{
if(a[j] > a[j + 1])
{
temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
}
}
for(i = 0; i < len; i++)
{
printf("%d ",a[i]);
}
}
4 快速排序
思想:每次以*cpbg为准,从后向前找到一个比他小的,从前向后找到一个比他大的,然后交换两者的值,内循环结束后就能够保证*cpbg左边的数都比他小,右边的数都比他大,及已经将*cpbg排序好了,然后将左右两边的数分别重复上述操作即可完成最终的排序。
#include <stdio.h>
void swap(int *a, int *b)
{
int temp = 0;
temp = *a;
*a = *b;
*b = temp;
}
void Qsort(int *begin, int *end)
{
int *cpbg = begin;
int *cped = end;
if(begin < end)
{
while(begin < end)
{
while(begin < end && *end >= *cpbg)//结束时*end < *cpbg,即从右往左找最小值。
{
end--;
}
while(begin < end && *begin <= *cpbg)//从左往右找最大值。
{
begin++;
}
swap(begin, end);
}
swap(cpbg, begin);
Qsort(cpbg, end-1);
Qsort(begin+1, cped);
}
}
int main(void)
{
int i = 0;
int a[10] = {10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
Qsort(a, a+9);
for(i = 0; i < 10; i++)
{
printf("%d ",a[i]);
}
printf("\n");
}