Why won't this print?

I have a function which basically sorts an array of 0's and 1's.

The array initially starts off as: 00110011

and I want the array to be sorted to look like: 00001111

One of my functions does this sorting through the lawnmower algorithm which is a basic sequential sort, but when it reaches the end of the array, it'll begin the sorting again immediately from right to left like a wrap around.

My problem is this:

I have a simple variable called passes, and this variable increments whenever a sort happens, so it just simulates how many "passes" the sorting algorithm needs to successfully sort this array

The problem I have is that, this passes will always say 0 instead of like 2 or 3.

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
51
52
void lawnmower(int *disk, int size)
{
	int passes = 0;
	int tempSize = size / 2;
	int total = 0;
	bool sorted = false;
	while (sorted == false)
	{
		for (int i = 0; i < tempSize; i++)
		{
			total += disk[i];
		}
		if (total == 0) //check to see if half of disks are black
		{
			cout << "Disks succesfully alternated!" << endl;
			cout << "Number of passes: " << passes << endl;
			for (int i = 0; i < size; i++)
			{
				cout << disk[i] << " ";
			}
			sorted = true;
		}
		else
		{
			sorted = false;
			total = 0;
			for (int i = 0; i < size; i++)
			{
				if (disk[i] == 1 && disk[i + 1] == 0)
				{
					disk[i] = 0;
					disk[i + 1] = 1;
					passes++;
				}
				if (i == size - 1) //beginnin sort from right to left
				{
					for (int j = size; j > 0; j--)
					{
						if (disk[i] == 0 && disk[i - 1] == 1)
						{
							disk[i] = 1;
							disk[i - 1] = 0;
							passes++;
						}
					}
				}
			}
		}

	}

}

> the lawnmower algorithm
¿this https://en.wikipedia.org/wiki/Cocktail_sorting ?

> sorts an array of 0's and 1's.
a simply count may suffice.

> sorted == false
comparing a bool will yield a bool. To be consistent, you ought to write (sorted==false) == true == true == true ... ad infinitum

> if (total == 0) //check to see if half of disks are black
that makes no sense, it is not a prerequisite that the array should be filled with equal amount of 0 and 1

> cout << "Disks succesfully alternated!" << endl;
your function shouldn't print anything


1
2
3
for (int i = 0; i < size; i++)
{
  if (disk[i] == 1 && disk[i + 1] == 0)
out of bounds, undefined behaviour.

1
2
3
4
if (i == size - 1) //useless
{
  for (int j = size; j > 0; j--) { //this shouldn't be inside the other loop
    if (disk[i] == 0 && disk[i - 1] == 1) // checking the same elements over and over again 

I fixed the issue, my array was already sorted from calling a previous sort function. I just had to re-populate the array to begin sorting with my lawnmower function
Topic archived. No new replies allowed.