What's Here?
- Members: 307,145
- Replies: 841,882
- Topics: 140,692
- Snippets: 4,468
- Tutorials: 1,165
- Total Online: 1,738
- Members: 110
- Guests: 1,628
|
Sorts an array of integers using the insertion sort algorithm (moving each element to its proper place). More efficient than Bubble Sort.
|
Submitted By: SPlutard
|
|
Rating:
 
|
|
Views: 35,232 |
Language: Java
|
|
Last Modified: August 9, 2006 |
Instructions: The following snippet is only a method - not a full-fledged applicaton, making it easier to add into your own code.
It requires two integer arguments (in this order):
--> The array to be sorted
--> The length of that array |
Snippet
/* Snippet: Insert Sort
* Author: SPlutard
*
*Description: Sorts an array of integers using the insertion sort algorithm (moving each element to its proper place).
* More efficient than Bubble Sort.
*/
public static void insertionSort(int[] list, int length) {
int firstOutOfOrder, location, temp;
for(firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++) { //Starts at second term, goes until the end of the array.
if(list[firstOutOfOrder] < list[firstOutOfOrder - 1]) { //If the two are out of order, we move the element to its rightful place.
temp = list[firstOutOfOrder];
location = firstOutOfOrder;
do { //Keep moving down the array until we find exactly where it's supposed to go.
list[location] = list[location-1];
location--;
}
while (location > 0 && list[location-1] > temp);
list[location] = temp;
}
}
}
Copy & Paste
|
|
|
|