Vector elements are not swapped in partition algorithm. - c++

Problem is from the Elements of Programming Interviews Book (2012).
Problem 6.1 pg 53: "Write a functions that take an array A (I used vector) and an index i into A, and rearranges the elements such that all elements less than A[i] appear first, followed by elements equal to A[i], followed by elements greater than A[i]. Your algorithm should have O(1) space complexity and O(|A|) time complexity.
My code doesn't do anything to the vector.
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void swapit(vector<T> v, int i, int j)
{
T temp;
temp = v[i];
v[i] = v[j];
v[j] = temp;
}
template <typename T>
void dutch_flag_partition(vector<T> &v, int pivotindex)
{
T pivot = v[pivotindex];
int lower = 0;
int equals = 0;
int larger = v.size() - 1;
while(equals <= larger)
{
cout << equals << " " << larger<< endl;
if(v[equals] < pivot)
{
swapit(v, lower++, equals++);
}
else if(v[equals] == pivot)
{
++equals;
}
else
{
swapit(v, equals, larger--);
}
}
}
int main()
{
int arr[] = {1,11,3,5,3,10,0,22,50,33,4,22,23,100,9};
vector<int> v (arr, arr + sizeof(arr)/sizeof(arr[0]));
dutch_flag_partition(v, 5);
for(int i = 0; i < v.size(); ++i)
{
cout << v[i] << " ";
}
cout << endl;
return 0;
}

void swapit(vector<T> v, int i, int j) { ... }
This does not modify the vector you passed in. Instead, it creates a copy for this function. You probably want to use a reference:
void swapit(vector<T> & v, int i, int j) { ... }

Related

Return min. and max. value simultaneously of an array using minimum number of comparisons

struct Pair
{
int min;
int max;
};
struct Pair getMinMax(int arr[], int n)
{
struct Pair minmax;
int i;
// If array has even number of elements
// then initialize the first two elements
// as minimum and maximum
if (n % 2 == 0)
{
if (arr[0] > arr[1])
{
minmax.max = arr[0];
minmax.min = arr[1];
}
else
{
minmax.min = arr[0];
minmax.max = arr[1];
}
// Set the starting index for loop
i = 2;
}
// If array has odd number of elements
// then initialize the first element as
// minimum and maximum
else
{
minmax.min = arr[0];
minmax.max = arr[0];
// Set the starting index for loop
i = 1;
}
// In the while loop, pick elements in
// pair and compare the pair with max
// and min so far
while (i < n - 1)
{
if (arr[i] > arr[i + 1])
{
if(arr[i] > minmax.max)
minmax.max = arr[i];
if(arr[i + 1] < minmax.min)
minmax.min = arr[i + 1];
}
else
{
if (arr[i + 1] > minmax.max)
minmax.max = arr[i + 1];
if (arr[i] < minmax.min)
minmax.min = arr[i];
}
// Increment the index by 2 as
// two elements are processed in loop
i += 2;
}
return minmax;
}
// Driver code
int main()
{
int arr[] = { 1000, 11, 445,
1, 330, 3000 };
int arr_size = 6;
Pair minmax = getMinMax(arr, arr_size);
cout << "nMinimum element is "
<< minmax.min << endl;
cout << "nMaximum element is "
<< minmax.max;
return 0;
}
In this qsn we have to return max and min value simultaneously so here struct is made.
I copied this code from GEEKSFORGEEKS site. I was trying this code's approach but stuck in doubt that how here comparisons is being calculates.
In this code i want to know that how comparisons is 3*(n-1)/2 when n=odd?
The above code is the definition of premature optimization. Where you literally are taking the below code that takes 4 int compares per two elements, down to 3, and the cost of making the code hard to read, and easier to write bugs into.
Even in the code written below these could be changed to if() else if(), since they are populated with the same value to start with, both conditions are impossible to be true. But it's not worth making that change to make the reader have to think through if that is actually true.
Trying to be too smart, and you'll only outsmart yourself.
struct Pair
{
int min;
int max;
};
Pair getMinMax(int arr[], int length){
Pair output = {0, 0};
if(length < 1){
return output;
}
output.min = arr[0];
output.max = arr[0];
for(int i= 1; i < length; i++){
if(arr[i] < output.min){
output.min = arr[i];
}
if(arr[i] > output.max){
output.max = arr[i];
}
}
return output;
}
int main()
{
int array[] = { 8, 6, 4, 2, 9, 4};
auto data = getMinMax(array, 6);
std::cout << data.min << " " << data.max;
}
Solution using STL code (C++20) :
#include <algorithm>
#include <vector>
#include <iostream>
struct MinMaxResult
{
int min;
int max;
};
MinMaxResult getMinMax(const std::vector<int>& values)
{
return (values.size() == 0) ?
MinMaxResult{} :
MinMaxResult(std::ranges::min(values), std::ranges::max(values));
}
int main()
{
std::vector<int> values{ 8, 6, 4, 2, 9, 4 };
auto data = getMinMax(values);
std::cout << data.min << ", " << data.max;
return 0;
}
There are answers (good ones imho), but so far none does actually count the number of comparisons. With std::minmax_element you can count the number of comparisons like this:
#include <utility>
#include <vector>
#include <iostream>
#include <algorithm>
template <typename TAG>
struct compare {
static size_t count;
template <typename T>
bool operator()(const T& a,const T& b){
++count;
return a < b;
}
};
template <typename TAG> size_t compare<TAG>::count = 0;
template <typename TAG>
compare<TAG> make_tagged_compare(TAG) { return {};}
int main()
{
std::vector<int> x{1,2,3};
auto c = make_tagged_compare([](){});
auto mm = std::minmax_element(x.begin(),x.end(),c);
std::cout << *mm.first << " " << *mm.second << " " << c.count;
}
Standard algorithms may copy predicates passed to them, hence count is static. Because I want to reuse compare later to count a different algorithm, I tagged it (each lambda expression is of different type, hence it can be used as unique tag). The output is:
1 3 3
It correctly finds min and max, 1 and 3, and needs 3 comparisons to achieve that.
Now if you want to compare this to a different algorithm, it will look very similar to the above. You pass a functor that compares elements and counts the number of comparisons of the algorithm. As example I use a skeleton implementation that does only a single comparison and either returns {x[0],x[1]} or {x[1],x[0]}:
template <typename IT, typename Compare>
auto dummy_minmax(IT first, IT last,Compare c) {
auto second = first+1;
if (c(*first,*second)) return std::pair(*first,*second);
else return std::pair(*second,*first);
}
int main()
{
std::vector<int> x{1,2,3};
auto c = make_tagged_compare([](){});
auto mm = std::minmax_element(x.begin(),x.end(),c);
std::cout << *mm.first << " " << *mm.second << " " << c.count << "\n";
double x2[] = {1.0,2.0,5.0};
auto c2 = make_tagged_compare([](){});
auto mm2 = dummy_minmax(std::begin(x2),std::end(x2),c2);
std::cout << mm2.first << " " << mm2.second << " " << c2.count;
}
Complete example

Array without a specified size without using vector [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Why aren't variable-length arrays part of the C++ standard?
(10 answers)
Closed 1 year ago.
I am trying to make a program that reads files with numbers and sort the numbers with different algorithms and there is multiple files that are going to be read and each file has a different amount of integers. so what i need to do is read those integers and cast them into a array.
but for some reason in c++ you cant have a array with an undefined size so what is a solution that i can use? And i can't use vectors (school project)
Here is my program
#ifndef SORT_H
#define SORT_H
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
// =============================================================================
// FILE READER
// =============================================================================
void fileReader(string fileName, int arr[]){
ifstream myfile(fileName);
int pos = 0;
string number;
if(myfile.is_open()){
while (getline(myfile, number))
{
arr[pos] = stoi(number);
pos++;
}
}
}
// =============================================================================
// SWAPER
// =============================================================================
void swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
// =============================================================================
// QUICKSORT
// =============================================================================
int partition(int arr[], int beg, int end){
int pivot = arr[end];
int index = beg - 1;
for(int j = beg; j < end; j++){
if(arr[j] <= pivot){
index++;
swap(&arr[index], &arr[j]);
}
}
swap(&arr[index+1], &arr[end]);
return (index+1);
}
void quicksortAlgo(int arr[], int beg, int end){
if(beg < end){
int pi = partition(arr, beg, end);
quicksortAlgo(arr, beg, pi-1);
quicksortAlgo(arr, pi+1, end);
}
}
template <typename T>
void quicksort(T arr[], int n)
{
quicksortAlgo(arr, 0, n-1);
for(int x = 0; x < n; x++)
cout << arr[x] << endl;
}
// =============================================================================
// HEAPSORT
// =============================================================================
void heapify(int arr[], int n, int i){
int max = i;
int left = 2*i + 1; // Left side
int right = 2*i + 2; // Right side
cout << "max: " << arr[max] << endl;
// if there is a left child for root and if is
// bigger then root
if(left < n && arr[max] < arr[left]){
max = left;
}
// If there is a right child of root and if is
// bigger then root
if(right < n && arr[max] < arr[right]){
max = right;
}
if(max != i){
swap(&arr[i], &arr[max]);
heapify(arr, n, max);
}
}
void heapsortAlgo(int arr[], int n){
for (int i = n/2 - 1; i >= 0; i--){
heapify(arr, n, i);
}
for (int i = n-1; i >= 0; i--){
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}
template <typename T>
void heapsort(T arr[], int n)
{
heapsortAlgo(arr, n);
for (int i = 0; i < n; i++){
cout << arr[i] << " ";
}
}
// =============================================================================
// INTSERTIONSORT
// =============================================================================
template <typename T>
void insertionsort(T arr[], int n)
{
int holePostion;
int valueToInsert;
for (int i = 1; i < n; i++){
valueToInsert = arr[i];
holePostion = i;
while(holePostion > 0 && arr[holePostion-1] > valueToInsert){
arr[holePostion] = arr[holePostion - 1];
holePostion = holePostion - 1;
}
arr[holePostion] = valueToInsert;
}
}
int main(){
string filedest;
string arrSize;
cout << "enter file destenation: ";
cin >> filedest;
int arr[];
int n = sizeof(arr) / sizeof(arr[0]);
fileReader(filedest, arr);
quicksort(arr, n);
return 0;
}
#endif
As #MikeCAT mentioned, you can use std::vector<T>.
You can add push elements at the back of the vector by std::vector<T>::push_back().
Alternatively, you can also resize the vector array by using std::vector<T>::resize() and then add elements at a specific location similar to what you are doing in your fileReader() function. You can also insert elements at a specific location by calling std::vector<T>::insert()
.
Do have a look at the time complexities if you have a time constraint in your programming task.

dynamic memory allocation using vectors and bubble sort

I need help in adding the user to enter value that becomes array size and will sort array by bubble sort its sorting however I need user to enter the value and it becomes value of an array ie. allocation memory dynamically
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap (int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort (std::vector<int> &array)
{
std::cout<<"Elements in the array: "<<array.size()<<std::endl;
//comparisons will be done n times
for (int i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for(int j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j+1])
Swap(&array[j], &array[j+1]);
}
}
}
//function to print the array
void PrintArray (std::vector<int> array)
{
for (int i = 0; i < array.size(); i++)
std::cout<<array[i]<<" ";
std::cout<<std::endl;
}
int main()
{
std::cout<<"Enter array to be sorted (-1 to end)\n";
std::vector<int> array;
int num = 0;
while (num != -1)
{
std::cin>>num;
if (num != -1)
//add elements to the vector container
array.push_back(num);
}
//sort the array
BubbleSort(array);
std::cout<<"Sorted array is as\n";
PrintArray(array);
return 0;
}
I tried cin using while however array doesn't print
I modified your version and show you, how you can get the number of elements to sort from the user and hot to dynamically allocate memory in your array.
You will simply use the std::vectors constructor to define a size. Looks then like: std::vector<int> array(numberOfElements);.
The whole adapted code:
#include <iostream>
#include <vector>
//function to swap values
//need to pass by reference to sort the original values and not just these copies
void Swap(int* a, int* b)
{
int temp = *a;
*a = *b;
*b = temp;
}
void BubbleSort(std::vector<int>& array)
{
std::cout << "Elements in the array: " << array.size() << std::endl;
//comparisons will be done n times
for (size_t i = 0; i < array.size(); i++)
{
//compare elemet to the next element, and swap if condition is true
for (size_t j = 0; j < array.size() - 1; j++)
{
if (array[j] > array[j + 1])
Swap(&array[j], &array[j + 1]);
}
}
}
//function to print the array
void PrintArray(std::vector<int> array)
{
for (size_t i = 0; i < array.size(); i++)
std::cout << array[i] << " ";
std::cout << std::endl;
}
int main()
{
std::cout << "Enter the number of data to sort: ";
size_t numberOfElements{ 0 };
std::cin >> numberOfElements;
std::vector<int> array(numberOfElements);
size_t counter{ 0 };
std::cout << "\nEnter "<< numberOfElements << " data\n";
int num = 0;
while ((counter < numberOfElements) &&(std::cin >> num) )
{
array[counter] = num;
++counter;
}
//sort the array
BubbleSort(array);
std::cout << "Sorted array is as\n";
PrintArray(array);
return 0;
}
But, I would recomend to use modenr C++ elements, like algorithms to solve the problem.
See:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
int main()
{
size_t numberOfElements{ 0 };
std::vector<int> array{};
std::cout << "Enter the number of data to sort: ";
std::cin >> numberOfElements;
std::cout << "\nEnter " << numberOfElements << " data values:\n";
std::copy_n(std::istream_iterator<int>(std::cin), numberOfElements, std::back_inserter(array));
std::sort(array.begin(), array.end());
std::cout << "\n\nSorted data:\n\n";
std::copy(array.begin(), array.end(), std::ostream_iterator<int>(std::cout, "\n"));
return 0;
}

Calling function from one class in another in C++

So, I am writing a program in C++ that has a function in the Sort class that I wish to call in the Main class. The function has several data members used that are present in that class, that are not present in the Main class and I keep getting a C2660 error, that "Function does not take 0 arguments". Is there a way (short of writing a bunch of getters and setters) to resolve this?
#include "Sort.h"
#include "Timer.h"
using namespace std;
int main
{
Sort *sort = new Sort();
Timer ti;
sort->SetRandomSeed(12345);
sort->InitArray();
cout << "starting InsertionSort" << endl;
ti.Start();
sort->InsertionSort();
ti.End();
cout << "Insertion sort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
//sort->InitList();
//cout << "starting InsertionSortList()" << endl;
//ti.Start();
//sort->InsertionSortList();
//ti.End();
//cout << "Insertion sort list duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting SelectionSort" << endl;
ti.Start();
sort->SelectionSort();
ti.End();
cout << "SelectionSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting MergeSort" << endl;
ti.Start();
sort->MergeSort();
ti.End();
cout << "MergeSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitArray();
cout << "starting QuickSort" << endl;
ti.Start();
sort->QuickSort();
ti.End();
cout << "QuickSort duration: " << ti.DurationInMilliSeconds() << "ms" << endl;
sort->InitVector();
cout << "starting std::sort() of Vector<int>" << endl;
ti.Start();
sort->VectorSort();
ti.End();
cout << "std::sort() duration: " << ti.DurationInNanoSeconds() << "ns" << endl;
delete sort;
cout << endl <<"Press [Enter] key to exit";
getchar();
}
Sort.cpp
//const int for array
int num = 10000000;
int val = 10000;
//array
int *tmpArray, *qArr, *insArr, *selArr, *mergArr = NULL;
int low, high;
//duration for timer
int duration = 0;
Sort::Sort()
{
}
Sort::~Sort()
{
}
void Sort::InitArray()
{
//int for index
int i = 0;
tmpArray = new int[num];
qArr = new int[num];
insArr = new int[num];
selArr = new int[num];
mergArr = new int[num];
//fill temp array with sequential numbers
for (int i = 0; i < num; i++)
{
tmpArray[i] = 1 + rand() % val;
}
for (i = 0; i < num; i++)
{
qArr[i] = tmpArray[i];
insArr[i] = tmpArray[i];
selArr[i] = tmpArray[i];
mergArr[i] = tmpArray[i];
}
low = qArr[0];
high = qArr[num - 1];
int n = sizeof(tmpArray) / sizeof(tmpArray[0]);
}
void Sort::InitVector()
{
vector<int> v(num);
std::generate(v.begin(), v.end(), std::rand);
}
void Sort::InitList()
{
// A set to store values
std::list<int> l;
// Loop until we get 50 unique random values
while (l.size() < num)
{
l.push_back(1 + rand() % val);
}
for (int n : l) {
std::cout << n << '\n';
}
}
//setting seed
void Sort::SetRandomSeed(unsigned int seed)
{
seed = rand();
}
void Sort::InsertionSort()
{
int i, key, j;
for (i = 1; i < n; i++)
{
key = insArr[i];
j = i - 1;
/* Move elements of arr[0..i-1], that are
greater than key, to one position ahead
of their current position */
while (j >= 0 && insArr[j] > key)
{
insArr[j + 1] = insArr[j];
j = j - 1;
}
insArr[j + 1] = key;
}
delete[] insArr;
insArr = NULL;
}
int Sort::partition(int qArr[], int low, int high)
{
int pivot = qArr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++)
{
// If current element is smaller than or
// equal to pivot
if (qArr[j] <= pivot)
{
i++; // increment index of smaller element
swap(&qArr[i], &qArr[j]);
}
}
swap(&qArr[i + 1], &qArr[high]);
return (i + 1);
}
void Sort::QuickSort(int qArr[], int low, int high)
{
if (low < high)
{
/* pi is partitioning index, arr[p] is now
at right place */
int pi = partition(qArr, low, high);
// Separately sort elements before
// partition and after partition
QuickSort(qArr, low, pi - 1);
QuickSort(qArr, pi + 1, high);
}
delete[] qArr;
qArr = NULL;
}
void Sort::SelectionSort()
{
int i, j, min_idx;
// One by one move boundary of unsorted subarray
for (i = 0; i < n - 1; i++)
{
// Find the minimum element in unsorted array
min_idx = i;
for (j = i + 1; j < n; j++)
if (selArr[j] < selArr[min_idx])
min_idx = j;
// Swap the found minimum element with the first element
swap(&selArr[min_idx], &selArr[i]);
}
delete[] selArr;
selArr = NULL;
}
void Sort::swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void Sort::VectorSort()
{
std::sort(v.begin(), v.end());
}
/* l is for left index and r is right index of the
sub-array of arr to be sorted */
void Sort::merge(int mergArr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int* L;
int* R;
/* create temp arrays */
L = new int[n1];
R = new int[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = mergArr[l + i];
for (j = 0; j < n2; j++)
R[j] = mergArr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
mergArr[k] = L[i];
i++;
}
else
{
mergArr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there
are any */
while (i < n1)
{
mergArr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there
are any */
while (j < n2)
{
mergArr[k] = R[j];
j++;
k++;
}
}
void Sort::MergeSort(int mergArr[], int l, int r)
{
if (l < r)
{
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
MergeSort(mergArr, l, m);
MergeSort(mergArr, m + 1, r);
merge(mergArr, l, m, r);
}
delete[] mergArr;
mergArr = NULL;
}
Sort.h
#include <iomanip>
#include <fstream>
#include <string>
#include <queue>
#include <stack>
#include <vector>
#include<iostream>
#include<cstdio>
#include<sstream>
#include<algorithm>
#include<list>
using namespace std;
#pragma once
class Sort
{
public:
Sort();
~Sort();
void InitArray();
void InitVector();
void InitList();
void SetRandomSeed(unsigned int seed);
int n, right, left, l, r, m;
vector<int> v;
void InsertionSort();
int partition(int qArr[], int low, int high);
void QuickSort(int qArr[], int low, int high);
void swap(int * xp, int * yp);
void VectorSort();
void MergeSort(int arr[], int l, int r);
void merge(int arr[], int l, int m, int r);
void SelectionSort();
};
Ignoring the Timer class (those are all good) here is the rest of the code. The C2660 errors are shown for the sort->MergeSort() and sort->QuickSort() calls in main.
I resolved the issues myself. I created helper functions in the Sort class that have no arguments and call the functions themselves to use in the main. Helper Functions shown below.
Sort.cpp
//method for Main to run to prevent C2660 errors
void Sort::mergeHelper()
{
MergeSort(mergArr, l, r);//call merge sort method
}
//method for Main to run to prevent C2660 errors
void Sort::quickHelper()
{
QuickSort(qArr, low, high);//call quick sort method
}
int Main
{
sort->quickHelper();
sort->mergeHelper();
}

How to use std::sort to sort an array in C++

How to use standard template library std::sort() to sort an array declared as
int v[2000];
Does C++ provide some function that can get the begin and end index of an array?
In C++0x/11 we get std::begin and std::end which are overloaded for arrays:
#include <algorithm>
int main(){
int v[2000];
std::sort(std::begin(v), std::end(v));
}
If you don't have access to C++0x, it isn't hard to write them yourself:
// for container with nested typedefs, non-const version
template<class Cont>
typename Cont::iterator begin(Cont& c){
return c.begin();
}
template<class Cont>
typename Cont::iterator end(Cont& c){
return c.end();
}
// const version
template<class Cont>
typename Cont::const_iterator begin(Cont const& c){
return c.begin();
}
template<class Cont>
typename Cont::const_iterator end(Cont const& c){
return c.end();
}
// overloads for C style arrays
template<class T, std::size_t N>
T* begin(T (&arr)[N]){
return &arr[0];
}
template<class T, std::size_t N>
T* end(T (&arr)[N]){
return arr + N;
}
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v, v + v_size);
In C++11:
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(), v.end());
If you don't know the size, you can use:
std::sort(v, v + sizeof v / sizeof v[0]);
Even if you do know the size, it's a good idea to code it this way as it will reduce the possibility of a bug if the array size is changed later.
You can sort it std::sort(v, v + 2000)
#include<iostream>
using namespace std;
void main()
{
int a[5];
int temp = 0;
cout << "Enter Values: " << endl;
for(int i = 0; i < 5; i++)
cin >> a[i];
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
cout << "Asending Series" << endl;
for(int i = 0; i < 5; i++)
{
cout << endl;
cout << a[i] << endl;
}
for(int i = 0; i < 5; i++)
for(int j = 0; j < 5; j++)
if(a[i] < a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
cout << "Desending Series" << endl;
for(int i = 0;i < 5; i++)
{
cout << endl;
cout << a[i] << endl;
}
}
you can use sort() in C++ STL. sort() function Syntax :
sort(array_name, array_name+size)
So you use sort(v, v+2000);
It is as simple as that ... C++ is providing you a function in STL (Standard Template Library) called sort which runs 20% to 50% faster than the hand-coded quick-sort.
Here is the sample code for it's usage:
std::sort(arr, arr + size);
//sort by number
bool sortByStartNumber(Player &p1, Player &p2) {
return p1.getStartNumber() < p2.getStartNumber();
}
//sort by string
bool sortByName(Player &p1, Player &p2) {
string s1 = p1.getFullName();
string s2 = p2.getFullName();
return s1.compare(s2) == -1;
}
With the Ranges library that is coming in C++20, you can use
ranges::sort(arr);
directly, where arr is a builtin array.
sort() can be applied on both array and vector in C++ to sort or re-arrange elements .
1. C++ sort() in case of a vector:
// importing vector, algorithm & iostream
using namespace std;
int main()
{
vector v = {5,4,3,2,8}; // depending on your vector size
sort(v.begin(), v.end());
cout<<v[1]; //testing the sorted element positions by printing
return 0;
}
2. C++ sort() in case of an array:
// including algorithm & iostream
using namespace std;
int main() {
int array[] = {10, 35, 85}; // array size 2000 in your case
int n = sizeof(array)/sizeof(array[0]);
sort(array, array+3);
cout<<array[0];
return 0;
}
Note: Both the above snippets were tested with modern C++ versions (11,17 & 20) before posting here .
sorting method without std::sort:
// sorting myArray ascending
int iTemp = 0;
for (int i = 0; i < ARRAYSIZE; i++)
{
for (int j = i + 1; j <= ARRAYSIZE; j++)
{
// for descending sort change '<' with '>'
if (myArray[j] < myArray[i])
{
iTemp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = iTemp;
}
}
}
Run complete example:
#include <iostream> // std::cout, std::endl /* http://en.cppreference.com/w/cpp/header/iostream */
#include <cstdlib> // srand(), rand() /* http://en.cppreference.com/w/cpp/header/cstdlib */
#include <ctime> // time() /* http://en.cppreference.com/w/cpp/header/ctime */
int main()
{
const int ARRAYSIZE = 10;
int myArray[ARRAYSIZE];
// populate myArray with random numbers from 1 to 1000
srand(time(0));
for (int i = 0; i < ARRAYSIZE; i++)
{
myArray[i] = rand()% 1000 + 1;
}
// print unsorted myArray
std::cout << "unsorted myArray: " << std::endl;
for (int i = 0; i < ARRAYSIZE; i++)
{
std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
}
std::cout << std::endl;
// sorting myArray ascending
int iTemp = 0;
for (int i = 0; i < ARRAYSIZE; i++)
{
for (int j = i + 1; j <= ARRAYSIZE; j++)
{
// for descending sort change '<' with '>'
if (myArray[j] < myArray[i])
{
iTemp = myArray[i];
myArray[i] = myArray[j];
myArray[j] = iTemp;
}
}
}
// print sorted myArray
std::cout << "sorted myArray: " << std::endl;
for (int i = 0; i < ARRAYSIZE; i++)
{
std::cout << "[" << i << "] -> " << myArray[i] << std::endl;
}
std::cout << std::endl;
return 0;
}
Use the C++ std::sort function:
#include <algorithm>
using namespace std;
int main()
{
vector<int> v(2000);
sort(v.begin(), v.end());
}
C++ sorting using sort function
#include <bits/stdc++.h>
using namespace std;
vector <int> v[100];
int main()
{
sort(v.begin(), v.end());
}
you can use,
std::sort(v.begin(),v.end());