Про сортировки!
Сортировки
Сообщений 1 страница 10 из 10
Поделиться201-02-2008 14:29:43
Сортировка вставками O(n^2)
Будем просматривать элементы массива A, начиная со второго. Каждый новый элемент А[i] будем вставлять на подходящее место в уже упорядоченную совокупность A[1], ..., A[i-1]. Это место определяется последовательными сравнениями элемента A[i] с упорядоченными элементами A[1], …, A[i-1].
Алгоритм на Pascal:
For j:=2 to n do
Begin
Key:=a[j];
{Вставка элемента A[j] в отсортированную последовательность A[1..j-1]}
I:=j-1;
While (i>0) and (A[i]>key) do
Begin
A[i+1]:=a[i];
Dec(i);
End;
A[i+1]:=key;
End;Поделиться301-02-2008 15:06:14
Ну вот и дошли до быстрой сортировки... Может, кому и полезно будет
Код:{ реурсивные алгоритмы: быстрая сортировка, см. программу внизу } { ----------------------------------------------------------------------- } { БЫСТРАЯ СОРТИРОВКА. } { Устанавливаем I=1 и J=N. Сравниваем элементы A[i] и A[J]. Если } { A[i]<=A[J], то уменьшаем J на 1 и проводим следующее сравнение элемен- } { тов A[i] с A[J]. Последовательное уменьшение индекса J и сравнение ука- } { занных элементов A[i] с A[J] продолжаем до тех пор, пока выполняется } { условие A[i] <= A[J]. Как только A[i] станет больше A[J], меняем места- } { ми элементы A[i] с A[J], увеличиваем индекс I на 1 и продолжаем сравне- } { ние элементов A[i] с A[J]. Последовательное увеличение индекса I и } { сравнение (элементов A[i] с A[J]) продолжаем до тех пор, пока выполня- } { ется условие A[i] <= A[J]. Как только A[i] станет больше A[J], опять } { меняем местами элементы A[i] с A[J], снова начинаем уменьшать J. } { Чередуя уменьшение J и увеличение I, сравнение и необходимые обме- } { ны, приходим к некоторому элементу, называемому пороговым или главным, } { характеризующим условие I=J. В результате элементы массива оказываются } { разделенными на две части так, что все элементы слева - меньше главного } { элемента, а все элементы справа - больше главного элемента. } { К этим массивам применяем рассмотренный алгоритм, получаем четыре } { части и т.д. Процесс закончим, когда массив A станет полностью отсорти- } { рованным. } { При программировании алгоритма "Быстрой сортировки" удобно исполь- } { зовать рекурентные вызовы процедуры сортировки (рекурсию). } { ----------------------------------------------------------------------- } var a:array[1..10] of integer; { массив элементов } n:integer; procedure QuickSort( L, R : Integer ); { Быстрая сортировка массива A[] } var i,j,x,y : integer; begin i := l; j := r; x := a[(l+r) div 2]; repeat while (A[i]<x) do inc(i); while (x<A[j]) do dec(j); if ( i<=j ) then begin y:=A[i]; a[i]:=a[j]; a[j]:=y; inc(i); dec(j); end; until (i>j); if (l<j) then QuickSort(l,j); if (i<r) then QuickSort(i,r); end; begin writeln('введите 10 элементов массива:'); for n:=1 to 10 do readln(a[n]); QuickSort( 1, 10 ); { на входе: левая и правая граница сортировки } writeln('после сортировки:'); for n:=1 to 10 do writeln(a[n]); end.
Поделиться401-02-2008 17:15:29
Ну а эт, сортировка слиянием))
function mergesort(s : TUzelUk; e : TUzelUk):TUzelUk;
Var
n,i,j : integer;
t1,t2,tp : TUzelUk;
l,r : TuzelUk;
res,rese : TUzelUk;
begin
t1:=s;
n:=0;
res:=nil;
while(t1<>nil) do begin
if(t1=e) then
break;
inc(n);
t1:=t1^.n;
end;
{trivialni pripad}
if(n = 1) then begin
add(res,rese,s^.v);
mergesort:=res;
exit;
end;
{rozdelovaci faze}
t1:=s;
i:=1;
while((t1<>nil)and(i<=(n div 2))) do begin
inc(i);
t1:=t1^.n;
end;
{rekurcia}
l:=mergesort(s,t1);
r:=mergesort(t1,e);
{slejvani}
t1:=l;
t2:=r;
while((t1<>nil)and(t2<>nil)) do begin
if(t1^.v<=t2^.v) then begin
add(res,rese,t1^.v);
t1:=t1^.n;
end else begin
add(res,rese,t2^.v);
t2:=t2^.n;
end;
end;
while(t1<>nil) do begin
add(res,rese,t1^.v);
t1:=t1^.n;
end;
while(t2<>nil) do begin
add(res,rese,t2^.v);
t2:=t2^.n;
end;
t1:=l;
while(t1<>nil) do begin
tp:=t1;
t1:=t1^.n;
dispose(tp);
end;
t1:=r;
while(t1<>nil) do begin
tp:=t1;
t1:=t1^.n;
dispose(tp);
end;
mergesort:=res;
end;Поделиться501-02-2008 17:18:53
Правда этим мало кто пользуется....
program DemonstrateHeapsort;
{$B-}
uses windos;
const MaxSize = 16000;
type dataType = integer;
heapType = array[1..MaxSize] of dataType;
procedure Adjust(var H : heapType; Root, Last : integer);
{ --------------------------------------------------------
Converts a semiheap into a heap.
Precondition: H is a semiheap rooted at position Root;
Last marks the end of the semiheap. $B- is in effect.
Postcondition: H is a heap rooted at position Root;
Last marks the end of the heap.
Method: Recursively trickles the item at position Root
down to its proper position by swapping it with its larger
child, if the child is larger than the item. If (2 * Root)
> Last, the item is at a leaf and nothing needs to be done.
-------------------------------------------------------- }
var Child, RightChild : integer;
Temp : dataType;
begin
if (2 * Root) <= Last
then { root is not a leaf }
begin
{ find index of larger child of root }
Child := 2 * Root; { index of root's left child }
RightChild := succ(Child); { right child, if any}
{ if there is a right child, find larger child }
if (RightChild <= Last) and (H[RightChild] > H[Child])
then Child := RightChild;
{ Child is the index of larger child of root }
{ if the value at position Root is smaller than
the value in the larger child, swap values }
if H[Root] < H[Child]
then
begin
{ swap }
Temp := H[Root];
H[Root] := H[Child];
H[Child] := Temp;
{ adjust the new subtree }
Adjust(H, Child, Last)
end { if }
end { if }
{ if root is a leaf, do nothing }
end; { Adjust }
procedure BuildHeap(var H : heapType; N : integer);
{ --------------------------------------------------------
Builds the initial heap.
Precondition: H is an array of N items.
Postcondition: H is a heap of N items.
-------------------------------------------------------- }
var Index : integer;
begin
for Index := N downto 1 do
{ tree rooted at Index is a semiheap -
transform it into a heap }
Adjust(H, Index, N)
end; { BuildHeap }
procedure Heapsort(var A: heapType; N : integer);
{ --------------------------------------------------------
Sorts an array by using heapsort.
Precondition: A is an array of N items.
Postcondition: A is sorted into ascending order.
-------------------------------------------------------- }
var Last : integer;
Temp : dataType;
begin
BuildHeap(A, N);{ build the initial heap }
for Last := N downto 2 do { heapsort }
{ loop invariant: A[1..Last] is a heap, A[Last+1..N] is
sorted and contains the largest elements of A }
begin
{ swap A[1] and A[Last] }
Temp := A[1];
A[1] := A[Last];
A[Last] := Temp;
{ change semiheap into a heap }
Adjust(A, 1, pred(Last))
end { for }
end; { Heapsort }
{ ******SAMPLE MAIN PROGRAM****** }
const Initialize = 870;
var A : HeapType;
N, Size : integer;
Hour : word;
Minute, Second : word;
Sec100 : word;
HeapSortOut: text;
begin
{ create an array of random integers }
{ Randomize; }
assign (HeapSortOut, 'a:HeapOut');
rewrite (HeapSortOut);
Randseed := Initialize;
Size := MaxSize;
for N := 1 to Size do
A[N] := random(2000);
writeln;
writeln(HeapSortOut);
writeln('This is a Heap Sort with an array size of', MaxSize:8, ' elements');
writeln(HeapSortOut,'This is a Heap Sort with an array size of', MaxSize:8, ' elements');
writeln('The array before sorting is: ');
writeln(HeapSortOut, 'The array before sorting is: ');
for N := 1 to 10 do
begin
write(A[N]:6);
write(HeapSortOut, A[N]:6);
end;
writeln;
writeln (HeapSortOut);
gettime (Hour, Minute, Second, Sec100);
writeln ('Start Time: ',Hour, 'Hour ':6, Minute, 'Minute ':8, Second,'Second ':9,
Sec100,' Hundredths of seconds ':14);
writeln (HeapSortOut,'Start Time: ',Hour, 'Hour ':6, Minute, 'Minute ':8, Second,'Second ':9,
Sec100,' Hundredths of seconds ':14);
{ sort the array }
HeapSort(A, Size);
gettime (Hour, Minute, Second, Sec100);
writeln ('End Time: ',Hour, 'Hour ':6, Minute, 'Minute ':8, Second,'Second ':9,
Sec100,' Hundredths of seconds ':14);
writeln (HeapSortOut,'End Time: ',Hour, 'Hour ':6, Minute, 'Minute ':8, Second,'Second ':9,
Sec100,' Hundredths of seconds ':14);
writeln('The array after sorting is: ');
writeln(HeapSortOut,'The array after sorting is: ');
for N := 1 to 15 do
begin
write(A[N]:4);
write(HeapSortOut, A[N]:4);
end;
close (HeapSortOut);
end.Поделиться601-02-2008 17:22:52
Еще один тип сортировки - это сортировка "Черпак". Она очень быста для небольших значений и небольших количеств элементов. Я ее лично усовершенствовал, чтобы терялось времени на исполнение алгоритма меньше.
var a,b :array[1..10000]of integer;
i,j,n,max :longint;
begin
fillchar(b,sizeof(b);0);
readln(n);
for i:=1 to n do
read(a[i]);
for i:=1 to n do
if a[i]>max
then max:=a[i];
for i:=1 to n do
inc(b[a[i]]);
for i:=0 to max do
write(i,' ');
end.Поделиться701-02-2008 17:28:09
когда то писал это, походу немного глючит, корочь, эффективно при сортировки строк.
program tree;
uses crt;
type pwl=^din; st=string[20];
din= record
inf:st;
left,right,top:pwl;
end;
var root,ed,rab,tek,pred:pwl;
f:text;
i,n:integer;
b,ex:boolean;
a:st;
//--------MR----------------------------------
Function mr(one,two:st):boolean;
var i,n:integer;
ex:boolean;
begin
if length(one)<length(two) then n:=length(one) else n:=length(two); i:=1; ex:=true;
while ex do
if one[i]<two[i] then
begin
mr:=true;
ex:=false; inc(i);
end
else if one[i]>two[i] then
begin
mr:=false;
ex:=false; inc(i);
end else begin ex:=true; inc(i); end;
end;
//-------mr end-----------------------------------
BEGIN clrscr;
assign(f,'inp.txt');
reset(f);
readln(f,n);
// ====Root==================================
new(root);
new(ed);
with ed^ do
begin
left:=nil;
right:=nil;
top:=nil
end;
With root^ do
begin
readln(f,inf);
top:=ed;
left:=nil;
right:=nil;
end;
//===Root==================================
//============================================
//==============Writing in tree begin=======================================
{for i:=1 to n-1 do}
while not eof(F) do
BEGIN
tek:=root;
ex:=true;
while ex do
begin
readln(f,a);
if mr(a,tek^.inf) and (tek^.left=nil)
then
begin
new(rab);
with rab^ do
begin
readln(f,inf);
left:=nil;
right:=nil;
top:=tek;
end;
tek^.left:=rab;
ex:=false;
end
else if mr(a,tek^.inf)=false and (tek^.right=nil)
then
begin
new(rab);
with rab^ do
begin
readln(f,a);
left:=nil;
right:=nil;
top:=tek;
end;
tek^.right:=rab;
ex:=false;
end
else if mr(a,tek^.inf)
then tek:=tek^.left
else tek:=tek^.right;
end;
END;
//=======================Writing in tree end====================================
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//=======================Reading in tree begin=================================
tek:=root;
i:=0;
while tek^.left<>nil do
tek:=tek^.left;
while tek^.top<>nil do
BEGIN
if tek^.right<>nil
then
tek:=tek^.right
else
if tek^.left<>nil
then
tek:=tek^.left
else
begin
writeln(tek^.inf);
rab:=tek;
tek:=tek^.top;
dispose(rab);
with tek^ do
begin
left:=nil;
right:=nil;
end;
end;
END;
//==================Reading tree end=====================================
readln;
END.Поделиться801-02-2008 17:48:20
сё больше незнаю...
Поделиться904-02-2008 14:02:33
+1 baitur
Продолжай в том же духе всегда и во в!!сем
Похожие темы
| Задачи по сортировкам | Задачи по программированию | 28-12-2008 |
| Вопрос по MySQL | Библиотеки, модули и компоненты | 08-03-2008 |