2016.5.7
一晚上学&写了冒泡和快排,其他六种留坑待更
冒泡
Python(未加flag)
def Bubble(array): n = len(array) for i in range(n-1): for j in range(n-1,i,-1): if array[j] < array[j-1]: array[j], array[j-1] = array[j-1], array[j] return
C++(加flag)
void Bubble(int *array, int n) { int i, j, temp; bool flag; for(i = 0; i < n-1; i ++) { flag = false; for(j = n-1; j > i; j --) { if(array[j] < array[j-1]) { temp = array[j]; array[j] = array[j-1]; array[j-1] = temp; flag = true; } } if(!flag) break; } }
快排
python(left为基准,两指针,一从右往左,一从左往右)
def QuickSort(array,left,right): if left >= right: return array key = array[left] low, high = left, right while left < right: while left < right and array[right] >= key: right -= 1 array[left] = array[right] while left < right and array[left] <= key: left += 1 array[right] = array[left] array[right] = key QuickSort(array, low, left - 1) QuickSort(array, right + 1, high) return array
C++(基准left可改为rand,两指针i,j,从左往右)
void QuickSort(int *array, int left, int right) { if(array == NULL || left < 0 || right < 0 || left >= right) { return; } const int base = array[left]; swap(array[left], array[right]); int i; int j = left - 1; for(i = left; i < right; ++i) { if(array[i] < base) if(i != ++j) swap(array[i],array[j]); } swap(array[++ j], array[right]); QuickSort(array, left, j - 1); QuickSort(array, j + 1, right); } void swap(int &val1, int &val2) { int temp = val1; val1 = val2; val2 = temp; }