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.
Related
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);
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
I am learning c++ and I am currently at halt.
I am trying to write a function such that:
It takes in input a one dimensional vector and an integer which specifies a row.
The numbers on that row are put into an output vector for later use.
The only issue is that this online course states that I must use another function that I have made before that allows a 1d vector with one index be able to have two indexes.
it is:
int twod_to_oned(int row, int col, int rowlen){
return row*rowlen+col;
}
logically what I am trying to do:
I use this function to store the input vector into a temporary vector as a 2D matric with i as the x axis and y as the y axis.
from there I have a loop which reads out the numbers on the row needed and stores it in the output vector.
so far I have:
void get_row(int r, const std::vector<int>& in, std::vector<int>& out){
int rowlength = std::sqrt(in.size());
std::vector <int> temp;
for(int i = 0; i < rowlength; i++){ // i is vertical and j is horizontal
for(int j = 0; j < rowlength; j++){
temp[in[twod_to_oned(i,j,side)]]; // now stored as a 2D array(matrix?)
}
}
for(int i=r; i=r; i++){
for(int j=0; j< rowlength; j++){
out[temp[i][j]];
}
}
I'm pretty sure there is something wrong in the first and last loop which turns into a 2D matric then stores the row.
I starred the parts that are incomplete due to my lack of knowledge.
How could I overcome this issue? I would appreciate any help, Many thanks.
takes in input a one dimensional vector
but
int rowlength = std::sqrt(in.size());
The line of code appears to assume that the input is actually a square two dimensional matrix ( i.e. same number of rows and columns ) So which is it? What if the number of elements in the in vector is not a perfect square?
This confusion about the input is likely to cuase your problem and should be sorted out before doing anything else.
I think what you wanted to do is the following:
void get_row(int r, const std::vector<int>& in, std::vector<int>& out) {
int rowlength = std::sqrt(in.size());
std::vector<std::vector<int>> temp; // now a 2D vector (vector of vectors)
for(int i = 0; i < rowlength; i++) {
temp.emplace_back(); // for each row, we need to emplace it
for(int j = 0; j < rowlength; j++) {
// we need to copy every value to the i-th row
temp[i].push_back(in[twod_to_oned(i, j, rowlength)]);
}
}
for(int j = 0; j < rowlength; j++) {
// we copy the r-th row to out
out.push_back(temp[r][j]);
}
}
Your solution used std::vector<int> instead of std::vector<std::vector<int>>. The former does not support accessing elements by [][] syntax.
You were also assigning to that vector out of its bounds. That lead to undefined behaviour. Always use push_back or emplate_back to add elements. Use operator [] only to access the present data.
Lastly, the same holds true for inserting the row to out vector. Only you can know if the out vector holds enough elements. My solution assumes that out is empty, thus we need to push_back the entire row to it.
In addition: you might want to use std::vector::insert instead of manual for() loop. Consider replacing the third loop with:
out.insert(out.end(), temp[r].begin(), temp[r].end());
which may prove being more efficient and readable. The inner for() look of the first loop could also be replaced in such a way (or even better - one could emplace the vector using iterators obtained from the in vector). I highly advise you to try to implement that.
The output is a string of numbers of entire row/column instead of a single number. Can someone please help me in this?
int main() {
/* Enter your code here. Read input from STDIN. Print output to STDOUT */
int t;
cin>>t;
while(t--){
int n,m,cnt=0;
cin>>n>>m;
for(int i=0;i<=n+1;i++){
for(int j=0;j<=m+1;j++){
if(i==0||i==n+1||j==m+1||j==0) G[i][j]=0;
cin>>G[i][j];
}
}
cout<<G[1][2]<<endl;//this gives wrong o/p
return 0;
}
Most likely you are reading out of bounds due to a i <= n + 1 and j <= m + 1 conditions in your for loops thus invoking undefined behavior resulting in a corrupted stack which explains the output you are seeing. Modify the boundaries to:
i < n and j < m. Arrays are zero indexed in C++. First array element is accessed via somearray[0] and the last element is somearray[n-1] not somearray[n] which is what you are trying to access in your code. The same goes for multi-dimensional arrays. The statement of:
cout << G[i][j] << endl;
is wrongly placed outside the for loops. It should be inside the inner for loop. The array should be defined as a second statement in your while loop:
int G[n][m]; // Avoid VLAs
That being said variable length arrays are not part of the C++ standard and you should prefer std::vector and std::array to raw arrays.
Assuming G is a 2D array of size n x m, then you go out of bounds here:
for(int i=0;i<=n+1;i++) {
for(int j=0;j<=m+1;j++)
since array indexing starts from 0, and ends at size - 1.
As a result, your code invokes Undefined Behavior. To avoid that, simply change your double for loop to this:
for(int i = 0; i < n; i++) {
for(int j = 0;j < m; j++)
So here's what I have so far:
void sortArray(int amountOfScores, int* testScores)
{
for(int i = 0; i < amountOfScores; i++)
{
for(int j = 0; j < amountOfScores-1; j++)
{
if(*(testScores+i) > *(testScores+j+1))
{
int temp = *(testScores+j);
*(testScores+j) = *(testScores+j+1);
*(testScores+j+1) = temp;
}
}
}
for(int i = 0; i < amountOfScores; i++)
{
cout << *(testScores+i) << endl;
}
}
Basically I'm trying to read in however many numbers the user wants to input, then sort them in ascending order. Catch is I have to use pointers and I've never really understood them. This code above works for 3 numbers, however, adding any more causes it to not sort them...I've tried trouble shooting as best I could but without any knowledge in pointers I don't know what I'm looking for.
Thanks for the help!
You problem might be here:
if(*(testScores+i) > *(testScores+j+1))
Did you mean:
if(*(testScores+j) > *(testScores+j+1))
(Note i replaced by j).
btw, in Bubble sort, if there are no swaps, you should break. This will cause a speed up in some cases.
Bubble sort works the same no matter if you are talking an array or a linked list (pointers).
The only catch is that rather than swapping the location of two adjacent items in an array, you are swapping pointer values between two adjacent list elements.
The algorithm is the same.