I'm new to C++ and I'm trying to do this:
I have an array of N elements. User should be able to input all the elements of an array and a number K. After that I have to sort the array such that the first part (elements 1 to K) be sorted in ascending mode and the second part (elements K to N) be sorted in descending mode.
Sorting function is implemented by myself. I can use qsort from cstdlib
, but it's not so interesting.
I have coded for sorting an array, but I can't understand how to sort an array in two parts.
#include <iostream>
#include <string>
void print_array(int[], int);
void qsort(int[], int, int);
int main()
{
int array_length;
int *array, k;
std::cout << "Write array length: ";
std::cin >> array_length;
array = new int[array_length];
for (int i = 0; i < array_length; i++) {
std::cout << "Write " << i + 1 << " element: ";
std::cin >> array[i];
}
print_array(array, array_length);
do {
std::cout << "Write k: ";
std::cin >> k;
} while (k >= array_length);
qsort(array, 0, k);
print_array(array, array_length);
}
void print_array(int* array, int length) {
for (int i = 0; i < length; i++) {
std::cout << array[i] << "\n";
}
}
void qsort(int arr[], int fst, int last)
{
int i, j, pivot, tmp;
if (fst < last)
{
pivot = fst;
i = fst;
j = last;
while (i < j)
{
while (arr[i] <= arr[pivot] && i < last)
i++;
while (arr[j] > arr[pivot])
j--;
if (i < j)
{
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
}
tmp = arr[pivot];
arr[pivot] = arr[j];
arr[j] = tmp;
qsort(arr, fst, j - 1);
qsort(arr, j + 1, last);
}
}