Code Snippets

  

Java Source Code


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!




Insertion Sort

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
Actions:
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


  1. /* Snippet: Insert Sort
  2. * Author: SPlutard
  3. *
  4. *Description: Sorts an array of integers using the insertion sort algorithm (moving each element to its proper place).
  5. *              More efficient than Bubble Sort.
  6. */
  7.  
  8. public static void insertionSort(int[] list, int length) {
  9.     int firstOutOfOrder, location, temp;
  10.    
  11.     for(firstOutOfOrder = 1; firstOutOfOrder < length; firstOutOfOrder++) { //Starts at second term, goes until the end of the array.
  12.         if(list[firstOutOfOrder] < list[firstOutOfOrder - 1]) { //If the two are out of order, we move the element to its rightful place.
  13.             temp = list[firstOutOfOrder];
  14.             location = firstOutOfOrder;
  15.            
  16.             do { //Keep moving down the array until we find exactly where it's supposed to go.
  17.                 list[location] = list[location-1];
  18.                 location--;
  19.             }
  20.             while (location > 0 && list[location-1] > temp);
  21.            
  22.             list[location] = temp;
  23.         }
  24.     }
  25. }

Copy & Paste


Comments


chachejave 2008-04-14 14:05:02

I'm a noobe. I like the idea of the efficiency of this snippet but what does the statement under "do" accomplish, specifically "location--"?

Amelody 2008-07-11 21:53:14

nice tip!!!


Add comment


You must be registered and logged on to </dream.in.code> to leave comments.





Live Java Help!

Java Tutorials

Reference Sheets

Java Snippets

Bye Bye Ads

Free DIC T-Shirt

T-Shirt Example

Related Sites

Monthly Drawing

Thumb Drive

Partners

Top Contributors

Top 10 Kudos This Month
-->