Why is this recursive selection sort not working - c++

I tried to run the code but it just gets stuck. NO error no warning nothing.Is there a better way to write a recursive selection sort?
#include <iostream>
using namespace std;
void scan(int *arr, int size){
for(int i = 0; i < size; i++){
cin >> arr[i];
}
}
void print(int *arr, int size){
for(int i = 0; i < size; i++){
cout << arr[i] << " ";
}
cout << "\n";
}
void swap(int *p1, int *p2){
int temp = *p1;
*p1 = *p2;
*p2 = temp;
}
void insertion(int *arr, int size){
if(size <= 1)return;
int i, max = size - 1;
for(int i = 0; i < size; i++){
if(arr[i] > arr[max])max = i;
}
swap(&arr[max], &arr[i]);
insertion(arr, size - 1);
}
int main(){
int *arr;
int size;
cout << "Enter the size of the array - ";
cin >> size;
arr = (int*)malloc(size*sizeof(int));
cout << "Enter the elements of the array - ";
scan(arr, size);
print(arr, size);
insertion(arr, size);
print(arr, size);
}
I feel like there is something wrong with the base case of the recursion. How do you generally solve these types of problems.

There was 1 small problem in your code. When you call the swap function in the insertion function you have to call it with &arr[max] and &arr[size-1], you can also use i-1, as the value of i is size here.
Code Attached for insertion function
void insertion(int *arr, int size){
if(size <= 1)return;
int i, maxIndex = 0;
for(i = 0; i < size; i++){
if(arr[i] > arr[maxIndex]) maxIndex = i;
}
swap(&arr[maxIndex], &arr[size-1]);
insertion(arr, size - 1);
}
The way to debug are many, you can learn to use the gnu debugger which is gdb or use print statements to find out where your code is going wrong.

Related

I am unable to get my code to get the stride of 7 to work properly C++

The question I am trying to solve is the following:
Write a function that traverses (and prints) the element of an array with stride =7. To do this the update part in the loop will be i= (i+7) % n, where n is the array size.
Would this function visit all elements of the array? Try different array sizes to check when it is impossible to traverse all elements.
The code that I wrote below doesn't print the correct values in the arry even if the value of i is correct.
Can anyone help, I would really appreciate it.
#include <fstream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(3);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 3);
cout << "The Elements In The Array Stride 7 Are: " << endl;
for (int i = 0; i < 3; i++)
{
cout << arr[i] << " ";
}
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
arr[j] = arr[i];
}
}
The problem is in StrideArray you read back the modified values of arr.
void StrideArray(int arr[], int n)
{
int i = 0;
int puffer=new int[n];
for (int j = 0; j < n; j++)
{
i = (i + 7) % n;
puffer[j] = arr[i];
}
for (int j = 0; j < n; j++){
puffer[j] = arr[j];
}
debete[] puffer;
}
Is a good way to write the function.
Also it visits all element only if n isn't dividable by 7. So if n is not 7,14,21,...
Also to use cout you have to #include <iostream>
Your StrideArray function needs fixing; you are iterating over j but using i to index, which remains constant; and you are reassigning value at one index to another where as you are supposed to print it:
void StrideArray(int arr[], int n)
{
int i = 0;
for (int j = 0; j < n; j=j+7)
{
cout << arr[j] << endl;
}
}
I modified the rest of your code for demo:
#include <iostream>
#include <stdlib.h>
using namespace std;
int* CreateArray(int n);
void StrideArray(int arr[], int n);
int main()
{
int* arr = new int[3];
arr = CreateArray(21);
cout << "The Elements In The Array Are: " << endl;
for (int i = 0; i < 21; i++)
{
cout << arr[i] << " ";
}
cout << endl;
StrideArray(arr, 21);
delete[] arr;
return 0;
}
int* CreateArray(int n)
{
int* arr = new int[n];
for (int i = 0; i < n; i++)
{
arr[i] = (rand() % 100);
}
return arr;
}

Bubble sort with array size

I want to do bubble sort for n elements of arraylist. Instead of declaring the arraylist first like below, I want to create the arraylist using for loops.
So this is the code of declaring the arraylist first:
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int arr[] = {1, 2, 3, 4, 5};
int n = 5;
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
}
which I do not want to do.
I have made this, but I do not know why it does not work. I'm still quite new with C++. May I know what's the problem. Thank you so much.
// A function to implement bubble sort
void bubbleSort(int arr[], int n)
{
int i, j;
bool swapped;
int comparisons=0;
for (i = 0; i < n-1; i++) {
swapped = false;
// Last i elements are already in place
for (j = 0; j < n-i-1; j++)
{
comparisons++;
if (arr[j] > arr[j+1])
{
int temp = arr[j];
arr[j]=arr[j+1];
arr[j+1]=temp;
swapped = true;
}
}
if (swapped == false)
break;
}
cout << "Number of comparisons = " << comparisons << endl;
}
/* Function to print an array */
void printArray(int arr[], int size)
{
int i;
for (i = 0; i < size; i++)
cout << arr[i] << " ";
cout << endl;
}
There are two problems:
Arrays are 0-indexed.
Variable length array which is not really legal in C++.
So write main like:
// Driver code
int main()
{
int n = 5;
int* arr = new int[n];
for(int i=0; i<n; i++){
arr[i]=i+1;
cout<<arr[i];
cout<<endl;
}
bubbleSort(arr, n);
cout<<"Sorted array: \n";
printArray(arr, n);
delete[] arr;
}

Bubble Sort Algorithm in c++

#include <iostream>
using namespace std;
int list [50];
void bsort(int list[], int n);
void printArray(int list[], int n);
int main ()
{
for (int i = 100; i > 50; i--)
{
list[i] = i;
cout << list[i] << endl;
}
int n = sizeof(list) / sizeof(list[0]);
bsort(list, n);
printArray(list, n);
return 0;
}
void bsort(int list[], int n)
{
int i, j;
for (i = 0; i <= 48; i++)
{
for (j = i+1; j <= 49; j++)
{
int temp;
if (list[i] > list[j])
{
temp = list[i];
list[i] = list [j];
list[j] = temp;
}
}
}
}
void printArray(int list[], int n)
{
for (int i = 0; i < n; i++)
cout << list[i] << " ";
cout << endl;
}
I'm in an intro-level computer science course and I am currently trying to write a program that calls the function 'bsort' to arrange the elements of the array 'list' in increasing order but my output is 49 zeros and I am not sure why? My professor wanted us to initialize the array 'list' starting at 100 and ending with 51 (in decreasing order).
Your initialisation loop is incorrect. Try like this
for (int i = 0; i < 50; i++)
{
list[i] = 100 - i;
cout << list[i] << endl;
}
Your version did list[100] = 100, list[99] = 99, etc but the array only has size 50.

Converting User Input from int[] to char[][]

I made this program to take int array as input and sort it using quick sort, but i was wondering, how would i change this program that it takes char[][] as input (string array) and sort them alphabetically?
It works if theres just one string, but i wanna know what if someone wants array of strings
//following program sorts an array using quicksort alorithm
#include<iostream.h>
#include<conio.h>
void swap(int *a, int *b) //function to swap elements
{
int t;
t = *a;
*a = *b;
*b = t;
}
int partition(int arr[], int left, int right) //function takes last element as pivot and places all smaller elements on left of pivot and greater elements on right
{
int pivot=arr[right]; //Pivot
int i= (left-1); //index of smaller element
for(int j=left; j<=(right-1); j++)
{
if(arr[j]<=pivot) //if current element is smaller or equal to pivot, theyre swapped
{
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i+1], &arr[right]);
return (i+1);
}
void quicksort(int arr[], int left, int right) //left is starting index, right is last index
{
if(left<right)
{
int index=partition(arr,left,right);
quicksort(arr, left, index-1); //sort elements before and after partition
quicksort(arr, index+1, right);
}
}
void print(int *arr, int size) //function to print elements in array
{
for(int i=0; i<size; i++)
{
cout<<arr[i]<<" ";
}
}
int main()
{
int n; //to store no. of elements in array
char ch; //ch for choice
do{
int *arr=NULL; //dynamic int array
clrscr();
cout<<"\nEnter Number of Elements:";
cin>>n;
cout<<"\nEnter Elements in Array to be sorted:";
for(int i=0; i<n; i++)
{
cout<<"\nEnter "<<i<<"th element:";
cin>>arr[i];
}
quicksort(arr,0,(n-1));
cout<<"\nSorted Array= ";
print(arr,n);
delete arr;
cout<<"\nwanna sort again??(y/n):";
cin>>ch;
}while(ch=='Y'||ch=='y');
return 0;
}
The integer version in your code needs int *arr = new int[n]; to allocate array of integers.
To do this with array of strings, declare char **arr = new char*[n]; and use strdup to assign array of char to each string.
You should be able to use the standard qsort in older compilers, otherwise use this modified version of your quicksort. The main difference is the replacement of if(arr[j]<=pivot){} with if(strcmp(arr[j], pivot) <= 0){}
void swap(char* &a, char* &b)
{
char *t = a;
a = b;
b = t;
}
int partition(char** arr, int lo, int hi)
{
int i = lo - 1;
for(int j = lo; j < hi - 1; j++)
{
if(strcmp(arr[j], arr[hi]) < 0)
{
i++;
swap(arr[i], arr[j]);
}
}
if(strcmp(arr[hi], arr[i + 1]) < 0)
swap(arr[hi], arr[i + 1]);
return i + 1;
}
void quicksort(char** arr, int const lo, int const hi)
{
if(lo < hi)
{
int p = partition(arr, lo, hi);
quicksort(arr, lo, p);
quicksort(arr, p + 1, hi);
}
}
void print(char **arr, int size)
{
for(int i = 0; i<size; i++)
cout << arr[i] << ", ";
cout << "\n";
}
int main()
{
int n;
cout << "Enter Number of Elements: ";
cin >> n;
cout << "Enter Elements in Array to be sorted:\n";
char buf[255];
char **arr = new char*[n];
for(int i = 0; i < n; i++)
{
cout << "Enter " << i << "th element: ";
cin >> buf;
arr[i] = strdup(buf);
}
quicksort(arr, 0, (n - 1));
cout << "Sorted:\n";
print(arr, n);
cout << "\n";
for(int i = 0; i < n; i++)
free(arr[i]); //<=== edit**
delete[]arr;
return 0;
}
Edit 1: changed quicksort function
Edit 2: changed the cleanup. strdup has to be cleaned up with free

A function which will display the contents of an array being sorted c++ using insertion sort

I have error, which is highlighted "cout << array[i] << endl;" in this section. The line is under array[i]. The error is "argument list for class template "std::array" is missing ". i need a function to display the contents of an array, using an insertion sort. If this code is incorrect, does anyone know the code to output the contents of the array, using linear search.
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
int numbers[SIZE] = { 6,3,1,9,4,12,17,2 };
for (int i = 0; i < 8; i++)
{
cout << array[i] << endl;
}
system("pause");
}
const int SIZE = 8;
void insertionSort(int numbers[], int arraySize)
{
int i, j, insert;
for (i = 1; i < arraySize; i++)
{
insert = numbers[i];
j = i;
while ((j > 0) && (numbers[j - 1] > insert))
{
numbers[j] = numbers[j - 1];
j = j - 1;
}
numbers[j] = insert;
}
}
You didn't call your function insertionSort(int numbers[], int arraySize) in main(). Therefore nothing will happen to the original array.
Note that you need a return 0; statement inside int main(). And that you need to use numbers[i] instead of array[i]. And you need to set your insertionSort() to return "something" or to pass your numbers[] as a reference. Also not to forget about the function prototype before main().
This should work:
const int SIZE = 8;
void insertionSort(int [], int);
int main()
{
int numbers[SIZE] = { 6,3,1,9,4,12,17,2 };
insertionSort(numbers, SIZE);
for (int i = 0; i < 8; i++)
cout << numbers[i] << endl;
system("pause");
return 0;
}
void insertionSort(int MyArray[], int size)
{
int i, j, insert;
for (i = 1; i < size; i++){
insert = MyArray[i];
j = i;
while ((j > 0) && (MyArray[j - 1] > insert)){
MyArray[j] = MyArray[j - 1];
j = j - 1;}
MyArray[j] = insert;}
}