Solved

# insertion sort

Posted on 2003-11-09
188 Views
hi i'm looking for the code for an insertion sort.  it only needs to deal with a small array of integers. for example 6, 7, 4, 2, 1 . if i anyone can help i'd greatly appreciate it... thanks!
0
Question by:mitchweb1
• 3
• 2
• 2
• +1

LVL 15

Expert Comment

Sorry, that question stink of school homework, If you show the code you have made sofar we may be able to give usefull comments on how to improve it.

regards JakobA
0

LVL 5

Expert Comment

If you are just looking for a fast way to sort an array, then use the built in quicksort.
int[] myArray = {6,7,4,2,1};
Arrays.sort(myArray);

And if you are writing an insertion sort for homework, then post your code so we can help :)
0

Author Comment

nah doing some research into the different types of sorts, but not over familiar with the java language.

here is the code i've written, the problem is that it checks if i < i-1 and if so swaps, but then it increments i. i can't find how to compare whether the new value of i-1 is less than the value of i -2. thanks in advance

class insertion
{
public static void main(String[] args)
{
int[] num= {3, 1, 6, 6, 9, 7, 5, 8, 9, 4};
int i = 1;

while (i<num.length) {
int j = num[i];
int k = num[i-1];

if (num[i] < num[i-1]) {
num[i] = k;
num[i-1] = j;
}
i++;

}

System.out.println(" "+num[0]+num[1]+num[2]+num[3]+num[4]+num[5]+num[6]);

}

}
0

LVL 15

Expert Comment

This isn't the way an insertion sort works.

Insertion sort
------------------
"Sort by repeatedly taking the next item and inserting it into the final data structure in its proper order with respect to items already inserted."  - National Institute of Standards and Technology.

In order to achieve this in an array, you'll need to be doing lots of looping:

1) Start at the second int (assuming the first int on it's own is sorted ;-)) call this toBeSorted
2) Initialise a sortedItems count to 1
3) While more ints remain in the array
3.1)  Read the value at the index sortedItems
3.2)  Loop through existing data until an int is found that is less than the current int or the index equals sortedItems
3.3)  Take a temporary copy of the int that has been found (call this toBeMoved)
3.4)  Write toBeSorted into this location
3.5)     While current index < sortedItems count
3.5.1)      Take a temporary copy of the next item
3.5.2)       Write toBeMoved to this location

When the loop (3.5) gets to the end of the sortedItems count, it should overwrite the value that has just been inserted into the array.

Just a quick note:

To display the complete array at the end, replace the System.out.println with:

for (int x = 0; x < num.length; x++)
{
System.out.print(num[x] + " ");
}
System.out.println();
0

Author Comment

i may be wrong, but i believe that the insertion sort puts values into the right positions by comparing the new number with the one before it.
i.e
4 2 7 3 9 1 6 would start with second integer so
2 4 7 3 9 1 6 then the third, which is already higher than second, so move onto fourth which is 3 and is so less than 7
2 4 3 7 9 1 6... it is at this point my code doesn't do what i wish it to. it should now compare third with second
2 3 4 7 9 1 6 and so on

so any data before a chosen integer has already been sorted as in your quote

(think i'm more confused than ever)
0

LVL 15

Accepted Solution

jimmack earned 100 total points
There is another way to do this which is a little like the way you are describing.

"Sorting can be done in place by moving the next item past the end of the sorted items into place by repeatedly swapping it with the preceding item until it is in place - a linear search and move combined."  - NIST

From your sequence, this would mean:

4   2   7   3   9   1   6

sorting 2 (index 1)
2 - 4   7   3   9   1   6

sorting 7 (index 2)
2   4   7   3   9   1   6

sorting 3 (index 3)
2   4   3 - 7   9   1   6
2   3 - 4   7   9   1   6

sorting 9 (index 4)
2   3   4   7   9   1   6

sorting 1 (index 5)
2   3   4   7   1 - 9   6
2   3   4   1 - 7   9   6
2   3   1 - 4   7   9   6
2   1 - 3   4   7   9   6
1 - 2   3   4   7   9   6

sorting 6 (index 6)
1   2   3   4   7   6 - 9
1   2   3   4   6 - 7   9
0

LVL 15

Assisted Solution

JakobA earned 100 total points
take care to get your indentation correct and informative.

usually it is better to remember indexes than it is to remember the values those indexes point to.

while (i<num.length) {
int temp = num[i];        // value to be inserted
int k = i-1;                    // index of first value to be compared to
while ( k >= 0 && temp < num[k] ) {
num[k+1] = num[k];  // move bigger values up one cell
k--;                           //
}
num[k+1] = temp;      // insert this value in its proper place
i++                            // and get ready for the next
}

regards JakobA
0

LVL 15

Expert Comment

>> Venabil
Is there a tool/trick to make those short links to specific entries in the thread? They are nifty.
0

## Featured Post

### Suggested Solutions

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Basic understanding on "OO- Object Orientation" is needed for designing a logical solution to solve a problem. Basic OOAD is a prerequisite for a coder to ensure that they follow the basic design of OO. This would help developers to understand the b…
Viewers learn how to read error messages and identify possible mistakes that could cause hours of frustration. Coding is as much about debugging your code as it is about writing it. Define Error Message: Line Numbers: Type of Error: Break Down…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…