用go語言實現快排

{"type":"doc","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"面試的時候,常會讓你手寫快排代碼。思路清楚了,在10分鐘是可以寫出來的。關於快排,需要注意一下幾點:"}]},{"type":"bulletedlist","content":[{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"快排是本地排序"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"快排有遞歸"}]}]},{"type":"listitem","content":[{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"快排需要分割數據,分割函數(建議)以最後一個數據爲參考,將數據分割爲大小兩列,最後返回參考數據所在的位置"}]}]}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null},"content":[{"type":"text","text":"好的函數名可以更好地體現思路。這是最近重構的版本,重新修改了函數名,理順了一下思路,在這裏做個記錄。"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}},{"type":"codeblock","attrs":{"lang":"go"},"content":[{"type":"text","text":"package algorithm\n\nimport (\n\t\"math/rand\"\n\t\"testing\"\n\t\"time\"\n)\n\nfunc quickSort(data []int) {\n\tsortWithinScope(data, 0, len(data)-1)\n}\n\n// 在指定範圍內排序\nfunc sortWithinScope(data []int, start int, end int) {\n\tif start < end {\n\t\tpivot := partition(data, start, end)\n\t\tsortWithinScope(data, start, pivot-1)\n\t\tsortWithinScope(data, pivot+1, end)\n\t}\n}\n\n// 將指定範圍內的數據分成大小兩列,返回中間參考值的位置\nfunc partition(data []int, start int, end int) int {\n\tref := data[end]\n\tnextLowerIndex := start\n\tfor i := start; i < end; i++ {\n\t\tif data[i] < ref {\n\t\t\tdata[nextLowerIndex], data[i] = data[i], data[nextLowerIndex]\n\t\t\tnextLowerIndex++\n\t\t}\n\t}\n\tdata[nextLowerIndex], data[end] = data[end], data[nextLowerIndex]\n\treturn nextLowerIndex\n}\n\n// 比較兩列數據是否相同\nfunc equal(a, b []int) bool {\n\tif len(a) != len(b) {\n\t\treturn false\n\t}\n\tfor i, v := range a {\n\t\tif v != b[i] {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc TestEmpty(t *testing.T) {\n\tcount := 10\n\ttoSort := make([]int, 0)\n\texpect := make([]int, 0)\n\tfor i := 0; i < count; i++ {\n\t\ttoSort = append(toSort, i)\n\t\texpect = append(expect, i)\n\t}\n\n\t// 打亂有序數組\n\trand.Seed(time.Now().UnixNano())\n\trand.Shuffle(len(toSort), func(i, j int) { toSort[i], toSort[j] = toSort[j], toSort[i] })\n\n\tquickSort(toSort)\n\tif !equal(expect, toSort) {\n\t\tt.Error(\"soft failed\")\n\t}\n}\n"}]},{"type":"paragraph","attrs":{"indent":0,"number":0,"align":null,"origin":null}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章