How to do insertion sort using 2 arrays..(storing the sorted array in another array)

Hi,im currently trying to do insertion sort using 2 array and I've tried insertion sort using 1 array. The main idea for insertion sort using 2 array is to have an unsorted array, and then create another array that stores all numbers that have been sorted.

The algorithm for this code is like this, The element of array1(the unsorted array) will be inserted in array2 which initially is an array without any value. But, before the element in array1 gets to be inserted in array 2, it will check first at what position should the element(array1 element) be inserted in array2 in order to get a sorted array2. When it found its position in array2, then the element will be inserted and all elements in array2 will be a sorted element.

Last edited on
not exactly sure what your looking for but this works for my limited testing.

edited.. this is a little nicer.

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
void insert(int** p, int pos, int val, int size) {
	int* n = new int[size + 1];
	int* cc = *p + size;
	int* cc_n = n + size+1;
	while (cc > *p-1) {
		cc_n--;
		cc--;
		if (cc_n == &n[pos]) {
			*cc_n = val;
			cc_n--;
		}
		*cc_n = *cc;
	}
	delete *p;
	*p = n;
}
int main() {
	int* array = new int[8]{ 4,3,12,5,11,20,18,19 };

	insert(&array, 3, 49, 8);
	int* cc = array;
	while (cc < array+9) {
		cout << *cc << "\n";
		cc++;
	}
}
Last edited on
The algorithm for this code is like this, The element of array1(the unsorted array) will be inserted in array2 which initially is an array without any value. But, before the element in array1 gets to be inserted in array 2, it will check first at what position should the element(array1 element) be inserted in array2 in order to get a sorted array2. When it found its position in array2, then the element will be inserted and all elements in array2 will be a sorted element.
I'm guessing this is what you're asking for but this is probably the least efficient way to sort an array that I can possibly think of but here it is...
https://onlinegdb.com/8l2HgnW7C

I can't copy the code for whatever reason... I wrote it but idk.

Yes!! @markyrocks thats exactly what im looking for..Thank you so much!! you helped me a lot!..and yeah i know that's its the least efficient but i somehow need to use this method:)



Last edited on
Topic archived. No new replies allowed.