S
S
Sergey Saifulin2014-10-28 12:03:34
C++ / C#
Sergey Saifulin, 2014-10-28 12:03:34

How to sort a dynamic array?

It is necessary to implement in C++ using classes the sorting of a dynamic array by a two-sided extremum. Can you tell me why an unsorted array is displayed on the screen?

#include <iostream>
#include <cstdlib>

using namespace std;

class clSorting{
  public:
  int *Arr;
  int max, min, n, k, size; // сортировке подвергаются элементы массива с индексами от k до n
  clSorting();
  int lookingForMax();
  int lookingForMin();
  void swap(int a, int b);
  void sortThis();
  ~clSorting();
};

/* Конструктор класса */
clSorting::clSorting(){
  cout << "Please, input size of your array: ";
  cin >> n;
  size = n;
  cout << endl << "Thank you. Wait, please..." << endl;
  Arr = new int[n];
  for (int i = 0; i < n; i++){
    cout << "Input an element of array: ";
    cin >> Arr[i];
    cout << endl << "Got it.";
  }
  cout << endl;
}

/* Метод поиска максимума из массива, n - размер массива */
int clSorting::lookingForMax(){
  max = Arr[k];
  for (int i = k + 1; i < n; i++){
    if (Arr[i]>max) {
      max = Arr[i];
    }
  }
  return max;
}

/* Метод поиска минимума из массива, n - размер массива */
int clSorting::lookingForMin(){
  min = Arr[k];
  for (int i = k + 1; i < n; i++){
    if (Arr[i]<min) {
      min = Arr[i];
    }
  }
  return min;
}

/* Метод, который меняет два числа местами */
void clSorting::swap(int a, int b){
  a = a + b;
  b = a - b;
  a = a - b;
}

/* Метод сортировки массива размера n */
void clSorting::sortThis(){
  k = 0;
  while (k < n){
    swap(Arr[k], lookingForMin());
    k++;
    swap(lookingForMax(), Arr[n]);
    n--;
  }
}

int main(int argc, char** argv){
  clSorting *A = new clSorting();
  A->sortThis();
  cout << "I have sorted your massive:" << endl;
  for (int i = 0; i < A->size; i++){
    cout << A->Arr[i] << " ";
  }
  system("PAUSE");
  return 0;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
Power, 2014-10-28
@Power

Your "Method that swaps two numbers" doesn't actually do anything at all (passing arguments by value and all that). And you initially have the wrong approach - you remember min / max, but do not remember their indexes in the array.

A
algol, 2014-10-28
@algol

The code was originally written incorrectly. The best thing to do with it is to remove it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question