You are on page 1of 10

Sorting

Sorting is generally performed by repeatedly comparing pairs of array elements, and swapping them if they meet some criteria. The order in which these elements are compared differs depending on which sorting algorithm is used, and the criteria depends on how the list will be sorted (ascending or descending order)

Selection Sort
There are many ways to sort an array. Selection sort is probably the easiest sort to understand, which makes it a good candidate for teaching even though it is one of the slower sorts. Selection sort performs the following steps: 1) Starting at index 0, search the entire array to find the smallest value 2) Swap the smallest value found with the value at index 0 3) Repeat steps 1 & 2 starting from the next index In other words, were going to find the smallest element in the array, and put it in the first position. Then were going to find the next smallest element, and put it in the second position. This process will be repeated until we run out of elements.

Selection sort

Shell Sort
Instead of comparing adjacent elements, like the bubble sort, the shell sort repeatedly compares elements that are a certain distance away from each other (d represents this distance). The value of d starts out as half the input size and is halved after each pass through the array. The elements are compared and swapped when needed. The equation d = (N + 1) / 2 is used. Notice that only integer values are used for d since integer division is occurring.

SHELL SORT

Membalik Isi Array


Untuk menukar dua elemen larik diperlukan satu variabel yaitu temp dan tiga proses pemuatan (assignment) seperti pada gambar. Simpan isi elemen larik pertama ke variabel temp, kemudian salin isi elemen larik terakhir ke elemen pertama, dan akhirnya salin isi temp ke elemen terakhir. Bilangan n adalah indeks elemen terkahir

temp = n[i] n[i] =n[ j] n[ j] = temp Prosedur yang sama dilakukan untuk elemen ke-2,3,4 dst. Bila jumlah elemen larik adalah r maka nomor elemen tengah larik adalah t = r /2, yaitu hasil bagi bilangan bulat bilangan r dengan 2. Contoh: 6 / 2 = 3 5/2=2

10 11 12 13 14 15
(a) Proses Pembalikan isi larik

15 14 13 12 11 10
1

temp

(b) Proses pertukaran isi larik

4/18/2013

10

You might also like