Calling a sort function on an array c++ - c++

I am using an insertion sort function to sort a 5000 int ascending array. when i pass the array's address to the function call, i get [Error] name lookup of 'i' changed for ISO 'for' scoping [-fpermissive]. Maybe I should use a vector but I am unfamiliar with them. Maybe I coded something wrong?
#include <iostream>
#define SIZE 5000 //array size
using namespace std;
void insertionSort(int arr[], int length) {
int i, j, tmp;
for (i = 1; i < length; i++) {
j = i;
while (j > 0 && arr[j - 1] > arr[j]) {
tmp = arr[j];
arr[j] = arr[j - 1];
arr[j - 1] = tmp;
j--;
}
}
}
int main() {
int a[SIZE];
int count = 1;
for(int i=0; i<SIZE; i++) {
a[i] = count;
count++;
}
for(int i = 0; i < SIZE; i++) {
printf("%d\t", a[i]);
}
insertionSort(&a[i], SIZE);
}

You probably want to call
insertionSort(a, SIZE)

// insertionSort(&a[i], SIZE); Here you haven't declared i in funciton main(), only in your for loop. And the call to insertionSort is outside of your loop.
Passing (&a)[0] and a mean the same thing.

Related

How can I convert my heap sort program to use C++ standard containers (for example std::vector)?

I know how to code with C, however, this is my first time I try to use C++. And the use of VLAs(Variable Length Arrays) is not allowed in C++. So how can I convert this program to use C++ standard containers( for example std::vector) for the same instead of going the C route?
Instead of int arr[n]; in main(), use std::vector<int> arr(n); and what further changes I have to do? Please assist.
Here is my code,
#include<iostream>
using namespace std;
// A function to heapify the array.
void MaxHeapify(int a[], int i, int n)
{
int j, temp;
temp = a[i];
j = 2*i;
while (j <= n)
{
if (j < n && a[j+1] > a[j])
j = j+1;
// Break if parent value is already greater than child value.
if (temp > a[j])
break;
// Switching value with the parent node if temp < a[j].
else if (temp <= a[j])
{
a[j/2] = a[j];
j = 2*j;
}
}
a[j/2] = temp;
return;
}
void HeapSort(int a[], int n)
{
int i, temp;
for (i = n; i >= 2; i--)
{
// Storing maximum value at the end.
temp = a[i];
a[i] = a[1];
a[1] = temp;
// Building max heap of remaining element.
MaxHeapify(a, 1, i - 1);
}
}
void Build_MaxHeap(int a[], int n)
{
int i;
for(i = n/2; i >= 1; i--)
MaxHeapify(a, i, n);
}
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
n++;
int arr[n];
for(i = 1; i < n; i++)
{
cout<<"Enter element "<<i<<": ";
cin>>arr[i];
}
// Building max heap.
Build_MaxHeap(arr, n-1);
HeapSort(arr, n-1);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 1; i < n; i++)
cout<<"->"<<arr[i];
cout<<"\nTime Complexity: Best case = Avg case = Worst case = O(n logn)";
return 0;
}
And the use of VLAs(Variable Length Arrays) is not allowed in C++
I've just compiled your code in C++ and it works perfectly fine. Feel free to rephrase if you think I misunderstood you.
If you want to stick to arrays instead of std::vector you can use std::array. Otherwise in your case it would be mostly swapping int[] for vector<int> with & in function parameters.

Bubble Sorting Algorithm in C++

I'm trying to implement the bubble sorting algorithm to an array of integers, the function which sorts the array takes an array as a parameter and suppose to return the sorted array.
Here is the code:
#include <iostream>
using namespace std;
int* BubbleSort(int data[]){
for(int i=0; i<sizeof(data)/sizeof(data[0])-1; i++){
for(int j=0; j<sizeof(data)/sizeof(data[0])-1-i; j++){
if(data[j+1]>data[j]){
int temp = data[j+1];
data[j+1]=data[j];
data[j]=temp;
}
}
}
return data;
}
int main()
{
int data[]={8,4,9,7,6,5,13,11,10};
int *a=BubbleSort(data);
cout<<"{";
for(int i=0; i<sizeof(data)/sizeof(data[0]); i++){
cout<<a[i];
if(i==sizeof(data)/sizeof(data[0])-1){
cout<<"}"<<endl;
}else{
cout<<",";
}
}
return 0;
}
The output I'm getting:
{8,4,9,7,6,5,13,11,10}
You must pass in the size of the array because an array it decays to the pointer to its first element (element 0).
void BubbleSort(int data[], int size){
for(int i(0); i != size; ++i){
for(int j(i + 1); j != size; ++j){
if(data[i] > data[j]){
int temp = data[i];
data[i] = data[j];
data[j] = temp;
}
}
}
Maybe too late, but maybe in the future it will be useful,
Try to use this code
...
/**
* Sort array of integers with Bubble Sort Algorithm
*
* #param arr Array, which we should sort using this function
* #param arrSZ The size of the array
* #param order In which order array should be sort
*
* #return Sorted array of integers
*/
void bubbleSortInt(double arr[], int arrSz, string order = "ascending")
{
for (int i = 0; i < arrSz; ++i)
{
for (int j = 0; j < (arrSz - i - 1); ++j)
{
// Swapping process
if ((order == "descending") ? arr[j] < arr[j + 1] : arr[j] > arr[j + 1])
{
swap(arr[j], arr[j + 1]);
}
}
}
return; // Optional because it's a void function
}// end bubbleSortInt
...
Then use it in your main function like below,
...
double integers[array_size];
const int array_size = 10;
string order = "ascending";
bubbleSortInt(integers, array_size, order)
for (int i = 0; i < array_size; ++i)
{
cout << integers[i] << "\t";
}
...
Have a detailed look at the bubble sort algorithm -> https://github.com/teamroyalcoder/algorithms#bubble-sort-algorithm
This is a GitHub repo where you will find a bunch of algorithms with full details and source code written in c++ https://github.com/teamroyalcoder/algorithms

Incorrect implementation of C++ Selection sort. Any advise

I have tried to implement selection sort here. Please let me know what is wrong here and if there is anything wrong with the implementation of selection sort
#include <iostream>
using namespace std;
void selectionsort(int arr, int size)
{
int temp = 0;
int min = 0;
int i, j, k;
for (i = 0; i<size-1;i++)
{
min = arr[i];
for(j = i+1; j<size; j++)
{
if(arr[j] < min)
{
temp = min;
min = arr[j];
arr[j] = temp;
}
else if (arr[j] >= min)
{
continue;
}
}
}
for (k = 0; k <size; k++)
{
cout<<arr[k];
}
}
int main()
{
int arr1[] = {5, 3, 4, 2, 1};
int size = sizeof(arr1)/sizeof(arr1[0]);
selectionsort(arr1, size);
return 0;
}
Please let me know what is wrong here and if there is anything wrong with the implementation of selection sort.
Main problem in your code swapping does not work as intended in selection sort.
I would suggest to store index in min variable and swap values outside of second loop.
min = i;
for (j = i + 1; j<size; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
temp = arr[min];
arr[min] = arr[i];
arr[i] = temp;
And don't forget to change parameter type as it is commented already

c++ insertion sort error

When I compile, it gives error of read access violation. Other stack overflow posts says this is due to an infinite loop. I also saw that the value goes to a very large negative number. My guess is that it is because list[-1], but I do not know how to change it so it does not go past list[0].
Insertion sort code
void insertion_sort(int list[], int length) {
for (int i = 1; i < length; i++) {
for (int j = i; (j > 0) && (list[j] < list[j - 1]); j--) {
swap(list, list[j - 1], list[j]);
}
}
}
Swap function code
void swap(int list[], int & src, int & dest){
int temp = list[src];
list[src] = list[dest];
list[dest] = temp;
}
You are using the values of your sort as an index in your swap. Keep it simple.
This works.
void insertion_sort(int list[], int length) {
for (int i = 1; i < length; i++) {
for (int j = i; (j > 0) && (list[j] < list[j - 1]); j--) {
std::swap( list[j - 1], list[j] );
}
}
}
int main( )
{
int arr[ 100 ];
for( size_t i= 0; i < 100; ++i )
arr[ i ]= std::rand( );
insertion_sort( arr, 100 );
return 0;
}
Added:
As this looks like a class exercise. What you want to notice is that std::swap has no idea that your list exists. All it wants to know is what values you want to swap. So if you can't use the standard library, write your swap like the standard.
void insertion_sort(int list[], int length) {
for (int i = 1; i < length; i++) {
j = i;
while(j > 0 && list[j - 1] > list[j]){
swap(list, list[j], list[j-1]);
j--;
}
}
This should work for sorting least to greatest. The while loop does the job of checking if it needs to be swapped and checks the already "sorted" positions in the array if it needs to be swapped again.
Happy Coding.

How do I call the InsertionSort method here?

I have the following code.. The method should work but I'm having trouble passing the vector to a function. I searched around and found that vector can be passed as 'references' or 'values' and I tried both, but they didn't seem to work. Am I calling the method incorrectly or passing the vector in a wrong way? Either ways, what can I do to fix this? Thanks! :)
//insertion sort method
#include <iostream>
#include <vector>
using namespace std;
void insertionSort(int arr[], int n){
for(int i = 0; i < n; i++){
int temp = arr[i]; // element adjacent to left sorted array
int j = i - 1;
while(temp > arr[j] && j != 0){
arr[j] = arr[j - 1];
j--;
}
arr[j] = temp;
}
}
int main(){
int n, temp;
cin >> n;
vector <int> arr;
for(int i = 0; i < n; i++){
cin >> temp;
arr.push_back(temp);
}
insertionSort(arr, n);
for(int i = 0; i < n; i++)
cout << arr[i] << " ";
return 0;
}
The first parameter of the insertionSort(int arr[], int n) method is wrong.
You also processed the arr incorrectly. At first iteration, int j = 0 - 1 = -1; which is unexpected/ out of bound.
Please try this :
void insertionSort(vector <int> &arr, int n){
int i, j, temp;
for (i = 1; i < n; i++)
{
temp = arr[i];
j = i - 1;
while ((j >= 0) && (temp<arr[j]))
{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = temp;
}
}
Thanks !!!