插入排序:
Insert_Sort(int arr[],int length) { int key = 0; int j = 0; for (int index = 1; index < length; index++) { key = arr[index]; j = index - 1; //如果将While条件写为:arr[j] > key && j > 0,可能会出现越界异常 while(j >= 0 && arr[j] > key) { arr[j + 1] = arr[j]; j--; } arr[j + 1] = key; } }
递归方式插入排序:
Insert_Sort_Recursive(int arr[],int length) { if(length > 1) { length--; Insert_Sort_Recursive(arr,length); } int key = arr[length]; int i = length - 1; while(i >= 0 && arr[i] > key) { arr[i + 1] = arr[i]; i--; } arr[i + 1] = key; }
合并排序:
void Merge(int arr[],int startIndex,int middleIndex,int endIndex) { int leftLen = middleIndex - startIndex + 1; int rightLen = endIndex - middleIndex; int* leftArr = new int[leftLen]; int* rightArr = new int[rightLen]; for (int index = 0; index < leftLen; index++) { leftArr[index] = arr[startIndex + index]; } for (int index = 0; index < rightLen; index++) { rightArr[index] = arr[index + middleIndex + 1]; } int leftIndex = 0; int rightIndex = 0; for (int index = startIndex; index < (endIndex - startIndex + 1); index++) { if (leftIndex < leftLen && rightIndex < rightLen) { if(leftArr[leftIndex] <= rightArr[rightIndex]) { arr[index] = leftArr[leftIndex]; leftIndex++; } else { arr[index] = rightArr[rightIndex]; rightIndex++; } continue; } if(leftIndex < leftLen) { arr[index] = leftArr[leftIndex]; leftIndex++; } if(rightIndex < rightLen) { arr[index] = rightArr[rightIndex]; rightIndex++; } } delete[] rightArr; delete[] leftArr; } Merge_Sort(int arr[],int startIndex,int endIndex) { if (startIndex < endIndex) { int middlenIndex = (startIndex + endIndex) / 2; Merge_Sort(arr,startIndex,middlenIndex); Merge_Sort(arr,middlenIndex + 1,endIndex); Merge(arr,startIndex,middlenIndex,endIndex); } }
冒泡排序:
Bubble_Sort(int arr[],int length) { int temp = 0; for (int i = 0; i < length - 1; i++) { for (int j = 1; j < length - i; j++) { if(arr[j - 1] > arr[j]) { temp = arr[j - 1]; arr[j - 1] = arr[j]; arr[j] = temp; } } } }