2 Replies - 229 Views - Last Post: 17 July 2013 - 08:58 PM Rate Topic: -----

#1 blindsamuraicoder  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • 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

>> 



Thanks for reading,
blind.

Is This A Good Question/Topic? 0
  • +

Replies To: MATLAB implementation of InsertSort returns unexpected result set

#2 #define  Icon User is offline

  • Duke of Err
  • member icon

Reputation: 1311
  • View blog
  • Posts: 4,503
  • 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;


Was This Post Helpful? 0
  • +
  • -

#3 blindsamuraicoder  Icon User is offline

  • New D.I.C Head

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

Re: MATLAB implementation of InsertSort returns unexpected result set

Posted 17 July 2013 - 08:58 PM

Thank you :)
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1