Unexpected exit from do-while loop

Can someone explain me why i have unexpected exit form function arraySort() at the end of 1 loop?

Visual studio debuger wont show any errors

My task is to sort data array using index array, where V points to smallest element and index[v] points to next element

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include "stdafx.h"
#include "time.h"
#include <iostream>

using namespace std;
int main()
{
int data[5] = {22,80,20,98,88};
int index[5] = {1,2,3,4,-1};
int v = 0; //start 

cout << "1. Array Check" << endl << "*********************************" << endl;
	arrayCheck(data, index,v);

cout << endl << endl << "2. Sorting Array" << endl << "*********************************" << endl;
	arraySort(data, index, v);

cout << endl << endl << "3. Sorted array" << endl << "*********************************" << endl;
	arrayCheck(data, index, v);


1
2
3
4
5
void arrayCheck(int data[], int index[],int v) {
	for (int a = v; a != -1; a = index[a]) {
		cout << data[a] << " ";
	}
}


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
  void arraySort(int data[], int index[],int v) {
	int pt_a=0, counter=1, tmp=0,a=0;
	do {
			counter = 1; 
			pt_a = v; 
			a = v;
			do{
				if (data[a] > data[index[a]]) {
					
					if (v != a) {
						tmp = index[a];
						index[a] = index[tmp];
						index[tmp] = a;
						index[pt_a] = tmp;
						pt_a = tmp;
						a = tmp;
					}
					else {
						tmp = index[a];
						index[a] = index[tmp];
						index[tmp] = a;
						a = tmp;
						v = tmp;
					}
					counter=0;
				}
				else { pt_a = a;}
				
				a = index[a];
				
			}while (index[a] != -1);
			
	} while (counter != 0); //if counter = 1 exit
	
}
Last edited on
Interesting. You have an array 'index' that has as many elements as the data array, but it does not contain the index of the first element, and it does contain one invalid index (-1).

I presume that you attempt to sort that data indirectly, by updating the array 'index'. You do have a fundamental problem. The first element that you will always print is at index 0 no matter what the 'index' contains. If you had to "swap" the data[0], then some element of 'index' will have 0, the data[0] will be printed twice, and some data element is never printed.
Found my problem :) while (counter != 0); //if counter = 1 exit must be while (counter != 1);

Tnx keskiverto, yea i know that i need to insert data check after swap in this part
1
2
3
4
5
6
7
8
9
10
11
12
 
if (v != a) {
        tmp = index[a];
	index[a] = index[tmp];
	index[tmp] = a;
	index[pt_a] = tmp;
	pt_a = tmp;
	a = tmp;
        if (data[v]>data[tmp]){ //untested part of code
        v=tmp;
        }
}
Topic archived. No new replies allowed.