//// main.cpp// 1.1排序_冒泡排序//// Created by lujunjie on 2016/12/25.// Copyright © 2016年 陆俊杰. All rights reserved.//#includeusing namespace std;int* bubbleSort(int* A, int n);int main(int argc, const char * argv[]) { // 升序 操作: // 第一轮,从0元素开始与相邻元素对比,大的往后放,直到把最大值放到 len - 1 位置 // 第二轮,从0开始与相邻元素对比,把最大值放到len - 1 - i 位置 // ** len - 1; 倒数第二跟最后值对比 // ** len - 1 - i; 比较过得无需再对比 int arr[8] = { 5,33,66,77,11,44,55,22}; int len = 8; for (int i = 0; i< len - 1; i++) { for (int j = 0; j< len - 1 - i; j++) { if (arr[j] > arr[j+1]) { int tmp = arr[j]; arr[j] = arr[j+1]; arr[j+1] = tmp; } } } for (int i = 0; i< len; i++) { cout << arr[i] << " "; } cout << endl; return 0;}
//// main.cpp// 1.2排序_插入排序//// Created by lujunjie on 2016/12/25.// Copyright © 2016年 陆俊杰. All rights reserved.//#includeusing namespace std;int main(int argc, const char * argv[]) { int arr[13] = { 54,35,48,36,27,12,44,44,8,14,26,17,28}; int len = 13; for (int i = 0; i< len-1; i++) { if (arr[i] > arr[i+1]) { int index = i; int value = arr[i+1]; while (value < arr[index]) { // 移动位置 arr[index + 1] = arr[index]; index--; if (index< 0) { // 判断到[0] break; } } arr[index+1] = value;// 插入原来判断的哪个元素。 } } for (int i = 0; i< len; i++) { std::cout << arr[i] << " "; } return 0;}
//// main.cpp// 1.3排序_选择排序//// Created by lujunjie on 2016/12/25.// Copyright © 2016年 陆俊杰. All rights reserved.//#includeusing namespace std;int selectMinKey(int *arr,int from,int to){ int index = from; for (int i = from + 1; i arr[i]) { index = i; } } return index;}int main(int argc, const char * argv[]) { int arr[8] = { 5,33,66,77,11,44,55,22}; int len = 8; for (int i = 0; i< len; i++) { int min = i; for (int j = i + 1; j < len; j++) { if (arr[min] > arr[j]) { min = j; } } if (min!=i) { swap(arr[min], arr[i]); } } for (int i = 0; i< len; i++) { cout << arr[i] << " "; } cout << endl; return 0;}
//// main.cpp// 1.4排序_快速排序//// Created by lujunjie on 2016/12/26.// Copyright © 2016年 陆俊杰. All rights reserved.//#include// 4 high = [2] low = [2]// 2 3 4 5 6 8using namespace std;int partition(int *pArr,int arrlen,int low,int high){ // 保存标准值 int standardVal = pArr[low]; while (low < high) { while (low < high && pArr[high] >= standardVal) { high--; } if (low < high) { swap(pArr[low], pArr[high]); } while (low < high && pArr[low] <= standardVal) { low++; } if (low < high) { swap(pArr[low], pArr[high]); } } return low;}void quickSortImpl(int *pArr,int arrLen,int low,int high){ if (low < high) { // 第一步:找到中间值 int centerPoint = partition(pArr,arrLen,low,high); // 第二步:前半部分排序 quickSortImpl(pArr, arrLen, low, centerPoint-1); //第三步:后半部分排序 quickSortImpl(pArr, arrLen, centerPoint+1, high); }}int main(int argc, const char * argv[]) { int a[15] = { 54,35,48,36,27,12,44,44,8,14,26,17,28,999,11}; int size = 15; quickSortImpl(a, size, 0, size-1); for (int i = 0; i < size; i++) { std::cout << a[i] << " "; } return 0;}