700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 冒泡法和选择法 排序算法实现

冒泡法和选择法 排序算法实现

时间:2018-10-11 08:46:13

相关推荐

冒泡法和选择法 排序算法实现

@冒泡法和选择法 排序算法实现

void swap(int& a, int& b){int temp=0;temp = a;a = b;b = temp;}void bubble_sort(int a[], int n){int i,j;int temp;int flag = 1;//设置标志,如果第一次循环比较时没有发生交换,则说明数组是升序排序,不用排序,提前结束循环for(i=0; (i<n-1)&&(flag == 1); i++){flag = 0;for(j=0; j<n-i-1; j++){if(a[j] < a[j+1]){swap(a[j], a[j+1]);flag = 1;}}}}void select_sort(int a[], int n){int i, j;for(i=0; i<n-1; i++){for(j=i+1; j <n; j++){if(a[j] < a[i]){swap(a[i], a[j]);}}}}void select_sortwithflag(int a[], int n){int i, j, k;for(i=0; i<n-1; i++){k = i;for(j=i+1; j <n; j++){if(a[j] > a[k]){k = j;}}if(i != k){swap(a[i], a[k]);}}}int main(){int i = 0;int a[10]={100,102, 104,99, 88, 98, 110, 103,1,69};int b[10]={100,102, 104,99, 88, 98, 110, 103,1,69};printf("The bubble sort arithmetic:\r\n");printf("Before sort the data is :");for(i=0; i<10; i++){printf(" %d ", a[i]);}printf("\r\n");bubble_sort(a, 10);printf("After sort the Data is : ");for(i=0; i<10; i++){printf(" %d ", a[i]);}printf("\r\n");printf("The selection sort arithmetic:\r\n");printf("Before sort the data is :");for(i=0; i<10; i++){printf(" %d ", b[i]);}printf("\r\n");select_sort(b, 10);printf("After sort the Data is : ");for(i=0; i<10; i++){printf(" %d ", b[i]);}printf("\r\n");}

The output of validation.

[tcsh] hanwuwex@bjsxfrax001:/local/hanwuwex/work> ./demoThe bubble sort arithmetic:Before sort the data is : 100 102 104 99 88 98 110 103 1 69After sort the Data is : 110 104 103 102 100 99 98 88 69 1The selection sort arithmetic:Before sort the data is : 100 102 104 99 88 98 110 103 1 69After sort the Data is : 1 69 88 98 99 100 102 103 104 110[Linux] [tcsh] hanwuwex@bjsxfrax001:/local/hanwuwex/work>

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。