# MATLAB implementation of InsertSort returns unexpected result set

Page 1 of 1

## 2 Replies - 315 Views - Last Post: 17 July 2013 - 08:58 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=324885&amp;s=d895032a7c60eeece67973a67b3fcfa9&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 blindsamuraicoder

Reputation: 0
• Posts: 2
• Joined: 16-July 13

# MATLAB implementation of InsertSort returns unexpected result set

Posted 16 July 2013 - 01:14 AM

Hello everyone at </DIC>,

I have decided to learn to program in MATLAB (r2013a) so I can use Matlab to study
various fields of mathematics but mostly so I can study algorithm design and analyses in general.
Since I have plenty of generic programming experience (C++, MySQL, python) I though I would go straight to
implementing a simple algorithm, "Insertion Sort" as described in "Introduction to Algorithms 3rd ed"; and it isn't going well.

I have reviewed the syntax of the operators and structural satements but I just don't see the issue.
The function should take an array and sort it obviously, but instead it takes the second element in the array and writes it to each subsequent element in the array. On debug with breakpoints execution never seems to enter the while loop, I don't understand why the conditions are never met.
Source
```    function [ sortedSet ] = insertionSort( targetSet )

for outerIndex = 2:length(targetSet)
workingKey = targetSet(outerIndex);
innerIndex = outerIndex - 1;
while innerIndex > 0 && targetSet(innerIndex) >= workingKey
targetSet(innerIndex + 1) = targetSet(innerIndex);
innerIndex = innerIndex - 1;
end
targetSet(outerIndex + 1) = workingKey;
end
sortedSet = targetSet;
end

```

Execution
```>> A

A =

14    11     9    13    13    14    13    19     5    15

>> B = insertionSort(A)

B =

14    14    14    14    14    14    14    14    14    14    11

>>

```

blind.

Is This A Good Question/Topic? 0

## Replies To: MATLAB implementation of InsertSort returns unexpected result set

### #2 #define

• Duke of Err

Reputation: 1495
• Posts: 5,217
• Joined: 19-February 09

## Re: MATLAB implementation of InsertSort returns unexpected result set

Posted 16 July 2013 - 05:01 PM

Should this be using the innerIndex :

```10	    targetSet(outerIndex + 1) = workingKey;

```

### #3 blindsamuraicoder

Reputation: 0
• Posts: 2
• Joined: 16-July 13

## Re: MATLAB implementation of InsertSort returns unexpected result set

Posted 17 July 2013 - 08:58 PM

Thank you