exchange sort (bubblesort) compares two consecutive items in the list, and swap them if they are out...
TRANSCRIPT
Exchange sort (Bubblesort)
compares two consecutive items in the list, and swap them if they are out of order.
for (i=1;i<n;i++)
for(j=n-1;j>=i;j--)
if (a[j]<a[j-1]) {temp=a[j];
a[j]=a[j-1];
a[j-1]=temp;}
Bubblesort
начальный массив
i=2 i=3 i=4 i=5 i=6 i=7 i=8 44 06 06 06 06 06 06 06 55 44 12 12 12 12 12 12 12 55 44 18 18 18 18 18 42 12 55 44 42 42 42 42 94 42 18 55 44 44 44 44 18 94 42 42 55 55 55 55 06 18 94 67 67 67 67 67 67 67 67 94 94 94 94 94
int ilast;
i=n-1;
while (i>0)
{
ilast=0;
for(j=0;j<i;j++)
if (a[j]>a[j+1]) {temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
ilast=j;
}
i=ilast;
}
18 5 15 13 20
18 5 15 13 20
18 20 15 13 5
18 13 15 20 5
18 13 20 15 5
Pass 0
ilast=3
Pass1
18 13 20 15 5
5 13 20 15 18
5 18 20 15 13
5 15 20 18 13
ilast=2
5 15 20 18 13
5 15 20 18 13
Pass 2
ilast=0
O(n2)
Shaker sort
начальный массив ll=1 kk=7
2 7
2 6
3 6
3 3
44 06 06 06 06 55 44 44 12 12 12 55 12 44 18 42 12 42 18 42 94 42 55 42 44 18 94 18 55 55 06 18 67 67 67 67 67 94 94 94
O(n2)
Partition sort (Quicksort)
Pick a middle item (and call it mid);
scan the array from the left until an item a[i] > mid is found
scan from the right until an item a[j] < mid is found.
Exchange the two items and continue this scan and swap process until the two scans meet somewhere in the middle of the array O(n*log(n))
void sort(int a[], int low, int high){ …scanUp=low;scanDown=high;mid=(low+high)/2;item=a[mid];do { while (a[scanUp]<item) scanUp++; while (item<a[scanDown]) scanDown--; if (scanUp<=scanDown) { temp=a[scanUp]; a[scanUp]=a[scanDown]; a[scanDown]=temp; scanUp++; scanDown --; }}while (scanUp < scanDown);if (low<scanDown) sort(a,low, scanDown);if (scanUp <high) sort(a, scanUp,high);}
Finding the medianThe median of n items is defined as that item which is less or equal to half of the n items and which is larger or equal to the other half of the n items.
The median of
16 12 99 95 18 87 10
is 18.
The main idea is: finding the k-th smallest of n items.
k = n/2
int find(int a[],int first, int last, int k){while (first<last) { val=a[k]; i=first; j=last; do { while (a[i]<val) i++; while (a[j]>val) j--; if (i<=j) { temp=a[i]; a[i]=a[j]; a[j]=temp; i++; j--; } } while (j>=i); if (j<k) first=i; if (k<i) last=j; }return last;}
O(n*log(n))
Straight merging
1. Split the sequence into two halves, called A and B.
2. Merge A and B by combining single items into ordered pairs.
3. Repeat steps 1 and 2, merging ordered pairs into ordered quadruples.
4. Repeat the previous steps, merging quadruples into octets, and continue, until the entire sequence is ordered.
fC 6, 34, 1, 64, 89, -2, 12, 46, -78, 3, 11, 49, 80, 20
fA 6, 1, 89, 12, -78, 11, 80
fB 34, 64, -2, 46, 3, 49, 20
fC (6,34),(1,64),(-2,89),(12,46),(-8,3),(11,49),(20,80)
fA (6,34),(-2,89),(-78,3),(20,80)
fB (1,64),(12,46),(11,49)
fC (1,6,34,64),(-2,12,46,89),(-78,3,11,49),(20,80)
O(n*log(n))