Question

I'm trying to write a class that contains an array of numbers that you can sort with a function myArray.quicksort(). When creating a new Objekt of Array I pass the constructor the length and then fill it:

public: int Items[];

    /*-- Constructor --*/
    Array(int n){
        length = n;
        for(int i=0; i<length; i++){
            int zahl;
            Items[length];
            cout << "Item" << i << ": ";
            cin >> number;
            Items[i] = number;
        }
     ...

Right after creating the Array this function to print it out works just fine:

void Array::show(){
    for(int i=0; i<this->length; i++){
        cout << this->Items[i] << " ";
    }
}

However after I try to sort it it prints out nonsense:

void Array::quickSort(int left, int right){
  int i=left, j=right;
  int tmp;
  int pivot = this->Items[(left + right) / 2];

  while(i <= j){
        while (this->Items[i] > pivot)
              i++;
        while (this->Items[j] < pivot)
              j--;
        if (i <= j) {
              tmp = this->Items[i];
              this->Items[i] = this->Items[j];
              this->Items[j] = tmp;
              i++;
              j--;
        }
  };

  if (left < j)
        quickSort(left, j);
  if (i < right)
        quickSort(i, right);
}

I'm sure I totally mix up something with the array pointers.. But I can't seem to find a solution for it.
Where is the big flaw here?

Was it helpful?

Solution

Standard C++ does not have flexible array members (like C99 has).

You don't need your Array class, use std::vector<int> instead (or perhaps std::array with C++11 if the array length is a compile time constant)

If you want to declare your Array class containing Items, follow the hints in the comment of Joachim Pileborg, learn about the rule of three (in C++11, it became the rule of five), so declare:

int *Items;

in your class, then initialize it with

Items = new int[n];

in its constructor[s], and destroy it with

delete [] Items;

in your destructor.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top