用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}}]}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章