Questions about insertion sort

Hi

i need to make a algorithm for insertion sort but i need to do this in one array.
i thought about making a for and a while like
1
2
3
4
5
6
7
for()
{
   while()
   {
     
   }
}


any help appreciated
You want something in the terms of (a quick whoop up )
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int* InsertionSort(int* Array, int size)
{
	for( int i = 1; i < size; ++i )
	{
		int value = Array[i];
		int j = i - 1;

		while( j >= 0 && Array[j] > value )
		{
			Array[j + 1] = Array[j];
			j = j - 1;
		}
		Array[j + 1] = value;
	}

	return Array;
}

void PrintArray(int* Array, int size)
{
	for( int i = 0; i < size; i++ )
		std::cout << Array[i] << " ";
}

int main()
{
	// Seed the random number generator for purpose of filling the array with random ints
	srand( (unsigned)time(NULL) );
	int size = 0;
	std::cout << "How big would you like the array >> ";
	std::cin >> size;

	int* myArray = new int[size];

	for( int i = 0; i < size; i++ )
		myArray[i] = rand() % 100;

	std::cout << "Before Sort: " << std::endl;
	PrintArray(myArray, size);
	myArray = InsertionSort(myArray, size);
	std::cout << "\nAfter Sort: " << std::endl;
	PrintArray(myArray, size);

	return 0;
}


See if you can neaten it.
Taken from : http://en.wikipedia.org/wiki/Insertion_sort

1
2
3
4
5
6
7
8
9
10
11
12
13
14
insertionSort(array A)
begin
    for i := 1 to length[A] do
    begin
        value := A[i];
        j := i - 1;
        while j >= 0 and A[j] > value do
        begin
            A[j + 1] := A[j];
            j := j - 1;
        end;
        A[j + 1] := value;
    end;
end;
Thanks :) it worked fine
No problem - hope it makes sense. Read up about it on wiki to have a better understanding of how it works.
Topic archived. No new replies allowed.