int partition(std::vector<int>& tab, int size){
int pivot = rand() % size;
std::swap(tab[pivot], tab[0]);
int i = 1;
for(int j = 1; j < size; j++){
if(tab[j] < tab[0]){
std::swap(tab[i], tab[j]);
i++;
}
}
std::swap(tab[0], tab[i-1]);
return i-1;
}
This code is very closed to give me a fine sorted list of integers, but still not perfect so far. I just don't understand where it is wrong.
How can I modify partition() so that the unsorted results get well sorted?
You are always sorting the beginning of the vector. The two recursive calls need to work on distinct, non-overlapping parts of it. This can be done by adding a 3rd parameter to quicksort, specifying the start index in the vector to sort. This would then need to be passed to partition to only work inside that range.
The function prototypes would then look like:
void partition(std::vector<int>& tab, int start, int size);
void quicksort(std::vector<int>& unsorted_list, int start, int size);
Related
hi I'm trying to implement this double pivot function and then pass the found indices to the recursive quicksort function with three calls (arr, left, pivot_sx) / (arr, pivot_sx + 1, pivot_dx-1) / (arr, pivot_dx + 1, right). I know that the function is still incomplete and that I do not return the indexes most likely I will declare a pointer to which I will assign the value of the left index and the right index will simply return it with a return.
the code I wrote for now is this:
#include <iostream>
#include<time.h>
#include <utility>
using namespace std;
int double_partition(int a[],int left,int right){
if(a[left]>a[right]){std::swap(a[left],a[right]);}
int piv_sx=a[left];
int piv_dx=a[right];
int i_piv_sx=left;
int i_piv_dx=right;
int i=left+1;
int j=right-1;
while(i<=j){
if(a[i]<=piv_sx){
std::swap(a[i],a[i_piv_sx]);
i_piv_sx+=1;
}else if(a[i]>=piv_dx){
std::swap(a[i],a[i_piv_dx]);
i_piv_dx-=1;
}
i++;
}
return 0;
}
void printArray(int arr[], int size){
int i;
for (i=0; i < size; i++)
cout<<" "<<arr[i];
cout<<std::endl;
}
int main()
{
srand(time(NULL));
int n;
cout << "Enter the number of items:" << "\n";
cin >>n;
int *arr = new int(n);
for (int x = 0; x < n; x++) {
int num = rand() % 10000;
arr[x]=num;
}
printArray(arr,n);
double_partition(arr,0,n-1);
printArray(arr,n);
}
as we know the pivot on the left must be smaller than the one on the right so at the beginning I compare the two pivots and if the one on the left is greater then I make the exchange.
After doing this I save the values of the pivots in two variables which I will then need to make the various comparisons.
and then I do this while loop where I start i from left + 1 because I don't need to compare the first element because I already know the value since it corresponds to the left pivot so it would be a useless comparison same reasoning for j = right-1.
I do all the comparisons and in the end when I compile and run the code sometimes I find a correct result and sometimes I find an incorrect result.
Is there anything I'm not doing right? Could anyone help me?
I should find the array in the situation where the elements on the left are smaller than the left pivot, the elements in the center are greater than the left pivot but smaller than the right pivot and the elements on the right will be greater than the right pivot.
int *arr = new int(n); gives you 1 int, initialized with the value n.
You want int *arr = new int[n];, which gives you an array of n ints.
Also don't forget to delete the array with delete[] arr; when you do not need it anymore.
I need to solve a c++ problem but something doesn't work and i don't know why.
N numbers are given, divided in k sequences. I need to find out which sequences are equal, knowing that k divides n.
is the problem with some values as an example:
Here is the problem with some values as an example. (it's in romanian)
I tried something like this:
#include <bits/stdc++.h>
using namespace std;
bool compare(int a[], int b[], int n)
{
for(int i=1;i<=n;i++)
if(a[i]!=b[i])
return false;
return true;
}
int main()
{
int n, k;
int i, j, secv;
cin>>n>>k;
int flag=1, v[n];
for(i=1;i<=n;i++)
cin>>v[i];
secv=n/k;
for(i=1;i<k && flag==1;i++)
for(j=i+1; j<=k && flag==1; j++)
if(compare(v+i*secv, v+j*secv, secv)==true)
{
cout<<i<<" "<<j;
flag=0;
}
if(flag==1) cout<<"NU";
return 0;
}
If your array is of size k and you are iterating the first element at index 1 then there are two problems:
Your array will only be able to save k-1 elements because in memory an array's first element is at index 0.
Some of the default array functions like begin and size will include 0 index so it might produce unexpected results.
How an array is saved in memeory
An array name is just a placeholder to the continuous memory reference. So if you's starting your array with 1 then you're skipping through the first index.
The best practice is to start an array with index 0.
I am trying to make a program that sorts an array without using the sort function (that won't work with objects or structs). I have made the greater than one work, but the less than one keeps changing the greatest element in the array to a one and sorting it wrong, and when used with the greater than function, the first element is turned into a large number. Can someone please help me fix this or is it my compiler.
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++) {
for(int i = 0; i < size; i++) {
if(array[i] > array[i+1]){
int temp = array[i];
array[i] = array[i+1];
array[i+1] = temp;
}
}
}
}
You are not looping correctly. Looks like you are trying bubble sort which is:
void min_sort(int array[], const unsigned int size){
for(int k = 0; k < size; k++)
for(int i = k+1; i < size; i++)
if(array[i] < array[k]){
int temp = array[i];
array[i] = array[k];
array[k] = temp;
}
}
void min_sort(int array[], const unsigned int size)
{
for(int i=0;i<size-1;i++)
{
for(int j=0;j<size-1-i;j++)
{
if(array[j]>array[j+1])
{
swap(array[j] , array[j+1]);
}
}
}
}
I see that you are trying to implement the bubble sort algorithm. I have posted the code for bubble sort here. In bubble sort you basically compare the element at an index j and the element next to it at index j+1. If array[j] is greater than array[j+1] , you swap them using the swap() function or by using the temp method. The outer loop will run size - 1 times , and the inner loop will run size - 1 - i times because the last element will already be in place.
For Example we have an array of size 4 with elements such as :
array[i] = [100,90,8,10]
The bubble sort will sort it in the following steps :
90,100,8,10
90,8,100,10
90,8,10,100
8,90,10,100
8,10,90,100
8,10,90,100
See, the use of size-1-i . You can see the nested loop runs less number of times in each iteration of the outer loop.
There is only one mistake that your 2nd loop condition should be: i < size -1.
So it should be:
for (int i = 0; i < size -1; i++)
Your attempt at bubble sort is basically correct, you just have an out of bounds issue with your inner loop. During the inner loop's last run, i == size - 1, therefore i + 1 is equal to size, thus data[i+1] is out of range. Simply change the condition of your for to be i < size - 1.
Working example: https://godbolt.org/z/e5ohWPfTz
Hello everyone I am starting to learn Data structures and Algorithms and implemented bubble sort myself after learning the concept. Following is the code I have written with my understanding but the problem is it runs for only one cycle and does not sort recursively.
For example:
{ 5,1,4,2,8} is sorted one time -> {1,4,2,5,8,}
What can be the problem?
vector<int> bubble_sort(vector<int> vec){
int temp = 0;
for(int i = 0; i < vec.size()-1; i++){
temp = vec.at(i+1); // holds the adjacent element.
// the following loop swaps the adjacent elements if the previous one is big
if(vec.at(i) > vec.at(i+1)){
vec.at(i+1) = vec.at(i);
vec.at(i) = temp;
}
temp = 0;
}
for(int i = 0; i < vec.size()-1; i++){
if(vec.at(i) > vec.at(i+1)){
bubble_sort(vec);
}
}
return vec;
}
Your function takes a vector<int> vector by copy, hence after first swaps only this copy is send to recursively sort.
Just add & to your function parameter: vector<int> bubble_sort(vector<int> &vec) and it should work
If you want to implement recursion fully and do not want to use for loop in the code, then follow this example. It will be helpful.
#include <iostream>
using namespace std;
/* Function to print an array */
void printArray(int arr[], int n)
{
for (int i=0; i <= n; i++)
cout<<arr[i];
}
void bubble_sort_recursive(int arr[], int j, int n) {
// base case
if (n==0 || j>n){
return;
}
// single pass has been completed and the higher element moved to right for that subarray
// now call the recursive function by keeping aside the already sorted positioned element
//i.e next pass wil start from this call
if (j == n){
bubble_sort_recursive(arr,0,n-1);
}
// swap consecutive 2 elements - main basic of bubble sort
if (arr[j]>arr[j+1]){
int t = arr[j];
arr[j] = arr[j+1];
arr[j+1] =t;
}
// go forward for next element of a single pass
bubble_sort_recursive(arr,j+1,n);
}
int main() {
int arr[] = {5,4,3,2,1};
// get the length of array
int n = sizeof(arr)/sizeof(arr[0]);
// call from 0 to len-1 as index starts from 0
bubble_sort_recursive(arr,0,n-1);
// print the sorted array
cout<<"Sorted array:"<<endl;
printArray(arr, n-1);
}
I have an assignment where I am given a list of events with a start time and end time and I need to make it schedule as many events as possible for that day assuming there is only one room to use. So the events are sorted by end time. The sorting algorithm I am supposed to implement is as follows:
sort() — a function to sort a floats array data[], creating an array of sorted indices. The sort() function does not sort the data, but fills the the array indx[] so that
data[indx[0]], data[indx[1]], ..., data[indx[NUM_EVENTS - 1]]
are the values of data[] in ascending order.
I am a little bit confused on what exactly it is asking but anyways this is what I have so far:
void sort(float data[], int indx[], int len){
int temp;
for (int i = 0; i < len; i++){
for (int j = 0; j < len; j++){
if (data[j] > data[j+1]){
temp = data[j];
indx[j] = data[j+1];
indx[j+1] = temp;
}
}
}
}
This code compiles but doesnt behave as it should. When I try to print what is in indx[] I get strange results. Any help is greatly appreciated. Thanks!
You are reading uninitialized memory. You are copying elements from data to indx, but only when data[j] > data[j + 1]. When that isn't true twice in a row, you have an element of indx that isn't assigned a value. It has an indeterminate value of random bits left by whatever used the memory before, and reading it is undefined behavior.