Skip to content
Tip: Compile in C99(for homeworks)

Stable Sorting

After it sorts arrays, any 2 record compared equal, will be in the same relative order. As they were before sorting, happens for every possible input array.

Im looking back at this and im not quite sure what this means, just look at this instead
EX
43431
BobTomAnnaJaneHenry
Stable Sort
13344
HenryTomJaneBobAnna
Unstable Sort
13344
HenryTomJaneAnnaBob

Essentially how it works is that it sorts group first (GPA) then puts names first by Input!

Insertion Sort

5,7,9,12,20 ==> | 5 | 7 | 9 | 12 | 20 |

Checks each number if it's greater than previous number.

  • If it's less than previous number it loops and sorts it correctly.
  • Else: Puts it at front.

Adaptive:

  • Time complexity depnds on Input
    • Almost Sorted = Faster, Else = slower
    • Best: Acending
    • Worst: Decending

unsorted: 20, 12, 9, 7, 5

(1)     20, *12* -> *12*, 20
(2)     12, 20, *9* -> *9*, 12, 20 
(3)     9, 12, 20, *7* -> *7*, 9, 12, 20
(4)     7, 9, 12, 20, *5* -> *5*, 7, 9, 12, 20

Total swaps:

  • 1 + 2 + 3 + 4
  • = 10
n=n(n1)2=542=10n=n(n1)2=n2n2=>n22n2

Psuedo Code

For i = 1; i <= n-1
{
    key = A[i]
    K = i - 1
    While ( K >= 0 && A[k] >= Key)
    {
        A[K + 1] = A[K]
        K--
    }
    A[K+1] = key
}

Steps for Devleoping Algorithms

  1. Draw Input data / Final
  2. Loops & Variables
  3. Property
    1. Identify Prop (relationship between data and loop iteration)
    2. i -> (i+1)
      1. State it for I
      2. State it for i + 1 ( know what to expect )
      3. Work out loop iteration i
      4. check loop I variant for i + 1
  4. Solved at the end
  5. Fix Start

Indirect Sorting

This uses insertion sort!

When to use Indirect sorting

  • When you cant modify the data
  • Or when theres too much data
IDXDataIDXData
000709010709
111115131115
222616252616
333201343201
444505424505
555427505427
666934666934
  • Very short explanation is that it sorts it by the index of the data
  • index 1 of the data is the smallest number 115, & index 6 is the largest at 934

Code

Essentially is insertion sort
for( i = 1; i < n; i++)
{
    key_idx = idxs[i];
    j = j - 1;
    while (j >= 0 && (data[idxs[j]] > data[key_idx]))
    {
        idxs[j+1] = idxs [j];
        j--;
    }
    idxs[j+1] = key_idx;
}
  • Reduces search in half

Example: guess my number, range is 0-100

0100>guess50x<50x>25x<37x=32

On her quizzes and exams this is something you would have to do (like saying what are the computed middle values)

LeftRightMiddleAction0115
063392 < 5051201
021392 > 2012427
222392 < 4273505
214616
FALSE=>Stop5709
6934