What's Here?
- Members: 99,783
- Replies: 389,612
- Topics: 58,612
- Snippets: 2,047
- Tutorials: 550
- Total Online: 1,552
- Members: 45
- Guests: 1,507
Who's Online?
|
Welcome to Dream.In.Code |
|
|
Getting Java Help is Easy!
Join 99,783 Java Programmers for FREE! Ask your question and get quick answers from experts. There are 1,552 online right now! We've got more than 500 tutorials and 2,000 snippets. Join and find out why Dream.In.Code is the #1 programming help community on the internet! Registration is fast and FREE... Join Now!
|
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: 12,426 |
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
|
|
|
Reference Sheets
Bye Bye Ads
Free DIC T-Shirt
Related Sites
Monthly Drawing
Partners
Top Contributors
Top 10 Kudos This Month
|