2011 年的最后一天了...
混合排序 -> 搅乱、重新洗牌; 以 Integer 动态数组为例.
//两个辅助函数 Swap、ToStr, 分别用于交换数组元素和呈现为字符串 procedure Swap(var Arr: TArray<Integer>; a,b: Cardinal); var tmp: Integer; begin if (a >= Length(Arr)) or (b >= Length(Arr)) or (a = b) then Exit; tmp := Arr[a]; Arr[a] := Arr[b]; Arr[b] := tmp; end; function ToStr(const Arr: TArray<Integer>): string; var n: Integer; begin for n in Arr do Result := Result + IntToStr(n) + sLineBreak; end; //----------------------------------------------------------------- {1、简单反排序} procedure SimpleShuffle(var Arr: TArray<Integer>); var r,i: Integer; //分别用作随机索引、遍历索引 begin for i := 0 to Length(Arr) - 1 do begin r := Random(Length(Arr)); Swap(Arr, i, r); end; end; {2、好的反排序} procedure GoodShuffle(var Arr: TArray<Integer>); var r,i: Integer; begin for i := Length(Arr) - 1 downto 0 do begin r := Random(i + 1); if r <> i then Swap(Arr, i, r); end; end; {测试} procedure TForm1.Button1Click(Sender: TObject); var arr1,arr2: TArray<Integer>; begin arr1 := TArray<Integer>.Create(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); // arr2 := Copy(arr1); // // SimpleShuffle(arr2); GoodShuffle(arr2); Memo1.Text := ToStr(arr1); Memo2.Text := ToStr(arr2); end;