Java School Assignment? Project Due Tomorrow? Chat LIVE With A Programming Expert!

 

Code Snippets

  

Java Source Code


Welcome to Dream.In.Code
Become a Java Expert!

Join 307,145 Java Programmers for FREE! Get instant access to thousands of Java experts, tutorials, code snippets, and more! There are 1,738 people online right now. 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: 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


  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!!!

aforlion 2009-02-20 08:43:02

I like this particular sort method. but how do I sort Strings instead of just int?

SooUoo 2009-10-29 15:18:38

you change string into integer by using "Integer.parseInt(args[])"


Add comment


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





Live Java Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

Java Tutorials

Reference Sheets

Java Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month