Shellsort
Shellsort
1
• Shell sort is a highly efficient sorting algorithm
and is based on insertion sort algorithm. This
algorithm avoids large shifts as in case of
insertion sort, if the smaller value is to the far
right and has to be moved to the far left.
3
Shell Sort Algorithm
• Following is the algorithm for shell sort.
4
procedure shellSort()
• A : array of items
• /* calculate interval*/
• while interval < A.length /3 do:
• interval = interval * 3 + 1
• end while
5
Shell Sort Algorithm
• Following is the algorithm for shell sort.
6
Pseudocode
7
• /* insert the number at hole position */
• A[inner] = valueToInsert
• end for
•
• /* calculate interval*/
• interval = (interval -1) /3;
• end while
• end procedure
8
• void shellSort(int arr[], int n){
• int gap, j, k;
• for(gap = n/2; gap > 0; gap = gap / 2) { //initially gap = n/2,
decreasing by gap /2
• for(j = gap; j<n; j++) {
• for(k = j-gap; k>=0; k -= gap) {
• if(arr[k+gap] >= arr[k])
• break;
• else {
• int temp;
• temp = arr[k+gap];
• arr[k+gap] = arr[k];
• arr[k] = temp;
• } } } }}
9
• int main(){
• int n;
• n = 5;
• int arr[5] = {33, 45, 62, 12, 98}; // initialize the array
• printf("Array before Sorting: ");
• for(int i = 0; i<n; i++)
• printf("%d ",arr[i]);
• printf("\n");
• shellSort(arr, n);
• printf("Array after Sorting: ");
• for(int i = 0; i<n; i++)
• printf("%d ", arr[i]);
• printf("\n");
• }
10