标签:c 冒泡排序 选择排序
数组的冒泡排序与选择排序
chunli@ubuntu:~/select$ cat main.c
#include <stdio.h>
#include <stdlib.h>
int swap_conut = 0 ; //记录交换次数
int loop_count = 0 ; //记录循环次数
void swap(int *a,int *b) //指针级 数据交换
{ //一个数连续异或同样的数两次,还是这个数
//相同位结果为0,不同位结果为1
*a = *a ^ *b;
*b = *a ^ *b;
*a = *a ^ *b;
swap_conut++;
}
int minkey(int array[],int low,int high)//在指定范围内,返回数组中最小数的下标
{
int key = array[low];
int min = low;
for(int i = low+1;i<high ;i++)
{
loop_count++;
if(key > array[i])
{
key = array[i];
min = i;
}
}
return min;
}
void select(int array[],int high) //选择排序
{
for(int i = 0;i<high;i++)
{
int j = minkey(array,i,high); //在i到high之间,返回最小数的下标
if(j!=i)
{
swap(&array[j],&array[i]);
}
}
}
void bubble(int array[],int len)
{
for(int i = 0;i<len;i++) //外循环次数
{
for(int j = 0;j<len-i-1;j++) //内循环每次比外循环少一次,巧妙减1
{
loop_count++;
if(array[j] > array[j+1]) //需要加1,上面的减一,巧妙的防止越界
{
swap(&array[j],&array[j+1]);
}
}
}
}
void traverse(int *array,int high) //遍历数组
{
for(int i = 0;i<high;i++)
{
printf("%d \n",array[i]);
}
}
int main()
{
int array[] = {9,8,7,6,5,4,3,2,1,0};
select(array,sizeof(array)/sizeof(int)); //开始排序
printf("选择法:交换次数%d ,循环次数 %d\n",swap_conut,loop_count);
traverse(array,sizeof(array)/sizeof(int)); //遍历输出
loop_count = 0;
swap_conut = 0;
int array1[] = {9,8,7,6,5,4,3,2,1,0};
bubble(array1,sizeof(array1)/sizeof(int)); //开始排序
printf("冒泡法:交换次数%d ,循环次数 %d\n",swap_conut,loop_count);
traverse(array1,sizeof(array1)/sizeof(int)); //遍历输出
return 0;
}编译运行: chunli@ubuntu:~/select$ gcc -std=c99 main.c && ./a.out 选择法:交换次数5 ,循环次数 45 0 1 2 3 4 5 6 7 8 9 冒泡法:交换次数45 ,循环次数 45 0 1 2 3 4 5 6 7 8 9
本文出自 “魂斗罗” 博客,请务必保留此出处http://990487026.blog.51cto.com/10133282/1787583
标签:c 冒泡排序 选择排序
原文地址:http://990487026.blog.51cto.com/10133282/1787583