Sorting algorithms/Insertion sort: Difference between revisions

From Rosetta Code
Content added Content deleted
 
(Added Java example.)
Line 10: Line 10:
j = j-1
j = j-1
A[j+1] = value
A[j+1] = value

Writing the algorithm for integers will suffice.

=={{header|Java}}==
public static void insertSort(int[] A){
for(int i = 1; i < A.length; i++){
int value = A[i];
int j = i - 1;
while(j >= 0 && A[j] > value){
A[j + 1] = A[j];
j = j - 1;
}
A[j + 1] = value;
}
}

Revision as of 20:39, 14 November 2007

Task
Sorting algorithms/Insertion sort
You are encouraged to solve this task according to the task description, using any language you may know.

An O(n^2) sorting algorithm which moves elements one at a time into the correct position. The algorithm is as follows (from the wikipedia):

insertionSort(array A)
        for i = 1 to length[A]-1 do
               value = A[i] 
               j = i-1
               while j >= 0 and A[j] > value do 
                        A[j + 1] = A[j]
                        j = j-1
               A[j+1] = value

Writing the algorithm for integers will suffice.

Java

public static void insertSort(int[] A){
	for(int i = 1; i < A.length; i++){
		int value = A[i];
		int j = i - 1;
		while(j >= 0 && A[j] > value){
			A[j + 1] = A[j];
			j = j - 1;
		}
		A[j + 1] = value;
	}
}