I was writing the quickSort()
function to sort an int[]
when I discovered this -well, I don't what should I call it- undefined behaviour
or error
or some kinda thing that I can't understand right now.
quickSort program:
// quick sort
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
// constant
enum {MAX = 10};
// class
class A
{
private:
int arr[MAX];
public:
A() // constructor
{
srand(time(0));
for(int i = 0; i < MAX; i++)
arr[i] = rand() % 100;
}
// accessing array
int get(int i)
{
return arr[i];
}
// quick sort
int Partition(int left, int right);
void quickSort(int left, int right);
void Swap(int&, int&);
};
// member function definition
int A::Partition(int left, int right)
{
int pivot = arr[right], i = left - 1;
for(int j = left; j <= right-1; j++)
{
if(arr[j] < pivot)
{
i++;
Swap(arr[i], arr[j]);
}
}
Swap(arr[i+1], arr[right]);
return i+1;
}
void A::quickSort(int left, int right)
{
if(left < right)
{
int pi = Partition(left, right);
quickSort(left, pi-1);
quickSort(pi+1, right);
}
}
void A::Swap(int& a, int& b)
{
a = a+b;
b = a-b;
a = a-b;
}
// driver
int main(void)
{
A obj1;
//-------Array initialized--------
cout << "Before sorting:" << endl;
for(int i = 0; i < MAX; i++)
cout << setw(4) << obj1.get(i);
//--------Sorting Array-----------
obj1.quickSort(0, MAX-1);
//--------Sorted Array------------
cout << "\nAfter sorting:" << endl;
for(int i = 0; i < MAX; i++)
cout << setw(4) << obj1.get(i);
return 0;
}
The problem is inside the swap()
function. When I am swapping the values using a int temp
variable, values gets swapped and array gets sorted in ascending order.
But when I am swapping the values without using a temporary int
variable, I'm getting 0
s in the sorted array. As shown below:
Output:
Before sorting:
89 43 18 98 23 88 52 18 1 25
After sorting:
1 18 0 0 25 43 0 88 89 98
When I debugged the swap()
, the parameters a
and b
were referring to the same address this
.