赞
踩
index | A | B | C | D | E | F |
---|---|---|---|---|---|---|
data | 2 | 6 | 5 | 1 | 4 | 3 |
len
个数要排序,需要 len-1
轮,第 i
轮需要比较 len-i
次。//用作两个数据交换的中间变量。 int temp = 0; /***为了直观,此处令i=1; i<len。但习惯上i一般从0算起, ***即i=0; i<len-1,这与i=1; i<len是等价的。 ***若令i=0; i<len-1,下一个循环内的j<len-1则需要改成j<len-1-i ***/ for (int i=1; i<len; i++) { for(int j=0; j<len-i; j++) { if(a[j] > a[j+1]) { temp = a[j]; a[j] = a[j+1]; a[j+1] = temp; } } }
完整代码
#include <stdio.h> #include <stdlib.h> void BubbleSort(int * list, int len); void TraverseList(int * list, int len); int main() { int * list = NULL; int len = 0; //Create a list you want to sort. printf("How many numbers do you want to sort: "); scanf("%d", &len); //Allocate the memory to save you numbers. list = (int *) malloc(len * sizeof(int)); //Save datas to the list. for (int i = 0; i < len; i++) { printf("Enter number%d: ", i+1); scanf("%d", &list[i]); } printf("************Before********************\n"); TraverseList(list, len); //sort the list. BubbleSort(list, len); printf("************After*********************\n"); TraverseList(list, len); return 0; } void BubbleSort(int * list, int len) { int temp; for (int i = 1; i < len; i++) { for (int j = 0; j < len-i; j++) { if (list[j] > list[j+1]) { temp = list[j]; list[j] = list[j+1]; list[j+1] = temp; } } } return; } void TraverseList(int * list, int len) { for (int i = 0; i < len; i++) { printf("%d ", list[i]); } printf("\n"); return; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。