Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- program merge;
- {$APPTYPE CONSOLE}
- {$R *.res}
- uses
- System.SysUtils;
- type
- MyArray = array of Integer;
- function FindIncreasingSequence(IntArray: MyArray): Integer;
- var
- Len, i: Integer;
- IsIncreasing: Boolean;
- begin
- Len := Length(INtArray) - 1;
- IsIncreasing := True;
- i := 0;
- while IsIncreasing and (i < Len) do
- begin
- if IntArray[i] > IntArray[i + 1] then
- IsIncreasing := False
- else
- Inc(i);
- end;
- if i = Len then
- FindIncreasingSequence := -1
- else
- FindIncreasingSequence := i;
- end;
- function MergeSort(IntArray: MyArray): MyArray;
- var
- ArrayLen, LeftIndex, RightIndex, LeftMax, RightMax, Index: Integer;
- LeftPart, RightPart: MyArray;
- i: Integer;
- begin
- Index := FindIncreasingSequence(IntArray);
- if Index <> -1 then
- begin
- ArrayLen := Length(IntArray) - 1;
- LeftPart := Copy(IntArray, 0, Index + 1);
- RightPart := MergeSort(Copy(IntArray, Index + 1, ArrayLen + 1));
- LeftIndex := 0;
- RightIndex := 0;
- LeftMax := Index;
- RightMax := Length(RightPart) - 1;
- for i := 0 to ArrayLen do
- begin
- if (LeftIndex <= LeftMax) and (RightIndex <= RightMax) then
- if LeftPart[LeftIndex] <= RightPart[RightIndex] then
- begin
- IntArray[i] := LeftPart[LeftIndex];
- Inc(LeftIndex);
- end
- else
- begin
- IntArray[i] := RightPart[RightIndex];
- Inc(RightIndex);
- end
- else
- if LeftIndex <= LeftMax then
- begin
- IntArray[i] := LeftPart[LeftIndex];
- Inc(LeftIndex);
- end
- else
- begin
- IntArray[i] := RightPart[RightIndex];
- Inc(RightIndex);
- end;
- end;
- end;
- MergeSort := IntArray;
- end;
- var
- IntArray: MyArray;
- i: Integer;
- begin
- Randomize;
- SetLength(IntArray, 10);
- for i := 0 to 9 do
- begin
- IntArray[i] := Random(20) - 10;
- Write(IntArray[i], ' ');
- end;
- IntArray := MergeSort(IntArray);
- Writeln;
- for i := 0 to 9 do
- begin
- Write(IntArray[i], ' ');
- end;
- Readln;
- end.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement