Sorting algorithms/Shell sort
You are encouraged to solve this task according to the task description, using any language you may know.
Sorting Algorithm
This is a sorting algorithm. It may be applied to a set of data in order to sort it.
For comparing various sorts, see compare sorts.
For other sorting algorithms, see sorting algorithms, or:
Heap sort | Merge sort | Patience sort | Quick sort
O(n log2n) sorts
Shell Sort
O(n2) sorts
Bubble sort |
Cocktail sort |
Cocktail sort with shifting bounds |
Comb sort |
Cycle sort |
Gnome sort |
Insertion sort |
Selection sort |
Strand sort
other sorts
Bead sort |
Bogo sort |
Common sorted list |
Composite structures sort |
Custom comparator sort |
Counting sort |
Disjoint sublist sort |
External sort |
Jort sort |
Lexicographical sort |
Natural sorting |
Order by pair comparisons |
Order disjoint list items |
Order two numerical lists |
Object identifier (OID) sort |
Pancake sort |
Quickselect |
Permutation sort |
Radix sort |
Ranking methods |
Remove duplicate elements |
Sleep sort |
Stooge sort |
[Sort letters of a string] |
Three variable sort |
Topological sort |
Tree sort
In this task, the goal is to sort an array of elements using the Shell sort algorithm, a diminishing increment sort.
Fortran
MODULE sort CONTAINS SUBROUTINE Shell_Sort(a) IMPLICIT NONE INTEGER :: i, j, increment REAL :: temp REAL, INTENT(in out) :: a(:) increment = SIZE(a) / 2 DO WHILE (increment > 0) DO i = increment+1, SIZE(a) j = i temp = a(i) DO WHILE (j >= increment+1 .AND. a(j-increment) > temp) a(j) = a(j-increment) j = j - increment END DO a(j) = temp END DO IF (increment == 2) THEN increment = 1 ELSE increment = increment * 5 / 11 END IF END DO END SUBROUTINE Shell_Sort END MODULE sort PROGRAM Shellsort USE sort IMPLICIT NONE REAL :: array(1000) CALL RANDOM_SEED CALL RANDOM_NUMBER(array) WRITE (*,*) "Unsorted array" WRITE (*,*) array WRITE (*,*) CALL Shell_Sort(array) WRITE (*,*) "Sorted array" WRITE (*,*) array END PROGRAM Shellsort
Java
This method will sort in place. If you want to preserve your unsorted array, use a copy of the array as an argument to this method. <java>public static void shell(int[] a) { int increment = a.length / 2; while (increment > 0) { for (int i = increment; i < a.length; i++) { int j = i; int temp = a[i]; while (j >= increment && a[j - increment] > temp) { a[j] = a[j - increment]; j -= increment; } a[j] = temp; } if (increment == 2) { increment = 1; } else { increment *= (5.0 / 11); } } }</java>