首页 > 代码库 > 3 个 n^2 的 排序
3 个 n^2 的 排序
冒泡排序
1: /* 因为冒泡是相邻交换, sign 标记着这次不用交换, 下次也不用交换. */ 2: #include <cstdio> 3: 4: int main(void) { 5: int sign = 1; 6: int a[10] = {1, 454, 634,34, 3, 3, 2343, 23435, 34, 42}; 7: 8: for(int i = 0; i < N-1 && sign; ++i) { 9: sign = 0; 10: for(int j = 0; j < N-1-i; ++j) { 11: if(a[j] > a[j+1]) { 12: int temp = a[j]; 13: a[j] = a[j+1]; 14: a[j+1] = temp; 15: sign = 1; 16: } 17: } 18: } 19: for(int i = 0; i < 10; ++i) { 20: printf("%d ", a[i]); 21: } 22: printf("\n"); 23: 24: return 0; 25: } 26:
选择排序
1: #include <cstdio> 2: 3: int main(void) { 4: int a[10] = {1, 454, 634,34, 3, 3, 2343, 23435, 34, 42}; 5: 6: for(int i = 0; i < 10-1; ++i) { 7: int k = i; 8: for(int j = i+1; j < 10; ++j) { 9: if(a[j] < a[k]) { // 选择出最小的 10: k = j; 11: } 12: } 13: if(k != i) { 14: int temp = a[k]; 15: a[k] = a[i]; 16: a[i] = temp; 17: } 18: } 19: 20: for(int i = 0; i < 10; ++i) { 21: printf("%d ", a[i]); 22: } 23: printf("\n"); 24: 25: return 0; 26: }
插入排序
1: #include <cstdio> 2: 3: int main(void) { 4: int a[10] = {1, 454, 634,34, 3, 3, 2343, 23435, 34, 42}; 5: int i, j; 6: 7: for(i = 1; i < 10; i++) { 8: int key = a[i]; 9: for(j = i-1; j >= 0; j--) { 10: if(key < a[j]) { 11: a[j+1] = a[j]; // 把牌一直向后推, 只要推完最后一个再插进去就是正确的 12: } 13: } 14: a[j+1] = key; // j 已经等于 -1 或者 已经越界, 需要加 1 15: } 16: 17: for(int i = 0; i < 10; ++i) { 18: printf("%d ", a[i]); 19: } 20: printf("\n"); 21: 22: return 0; 23: }
3 个 n^2 的 排序
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。