Please explain the code in this count sort - c++

I was learning count sort from tutorial and my C++ source code is given below:
#include <iostream>
#include <string.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int output[size];
//declare count array
int count[size];
//initialize count[] with zero
//memset ( void * ptr, int value, size_t num )
memset(count, 0, sizeof(count));
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
/*
Modify the count array such that each element at
each index stores the sum of previous counts.
*/
// i=1 because, previous is 0 due to avoid -1
for(int i=1; i<size; i++){
count[i] += count[i-1];
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
//***********THIS LINE***********
output[count[arr[i]]-1] = arr[i];
count[arr[i]]--;
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
// your code goes here
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}
I understand about taking sorted array in output array.However why we need to decrements the output index by -1:
output[count[arr[i]]-1] = arr[i];
I didn't understand this part. I try with only output[count[arr[i]]] but it doesn't gave me the correct sorted array.

The array of counts was converted in to an array of ending indices, point one past the end of each logical bucket, so 1 is subtracted from each index. This could be combined to use pre-decrement, and the array scanned backwards:
for(i=size; i; ){
i--;
output[--count[arr[i]]] = arr[i];
}
Getting back to the counts after they are summed up, note that count[0] contains a count of all the elements equal to zero, and count[1] contains a count of all elements == zero and all elements == 1, and so on, so count[0] is the logical size of the bucket that will contain the zeroes, and the size is 1 greater than the index to the last element. The same logic applies to count[1] and so on.
Example code where the counts are converted into starting indices. output[] converted to use new (to avoid stack overflow and some compilers don't support variable length arrays). count[10] assumes the range of numbers is limited to 0 through 9.
#include <iostream>
#include <stdlib.h>
using namespace std;
void countSort(int arr[], int size)
{
//declare output array
int * output = new int[size];
//declare count array
// assumes range of values is 0 to 9
int count[10];
//initialize count[] with zero
for(int i=0; i<size; i++)
count[i] = 0;
//input array element is the index of count array
//storing the repetition/frequency
for(int i=0; i<size; i++){
count[arr[i]]++;
}
// convert counts into starting indices (this is the main change)
int sum = 0, tmp;
for(int i=0; i<size; i++){
tmp = count[i];
count[i] = sum;
sum += tmp;
}
//Build ouput array
//count array element is the index of output array
for(int i=0; i<size; i++){
output[count[arr[i]]++] = arr[i];
}
//copy ouput array into input array arr[]
for(int i=0; i<size; i++){
arr[i] = output[i];
}
delete[] output;
}
void printArray(int arr[], int size){
// Ascending order
for(int i=0; i<size; i++){
cout<<arr[i]<<" ";
}
cout<<endl;
}
int main() {
int arr[] = {1,4,1,2,7,5,2,6,6,9};
int size= sizeof(arr)/sizeof(arr[0]);
countSort(arr, size);
printArray(arr, size);
return 0;
}

Related

Given an array of N elements. The task is to find the length of the longest subarray such that sum of the subarray is even

For the given question I have come up with the following code. But it doesn't seem to solve the problem. Please have a look and suggest changes.
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int maxim=INT_MIN;
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=arr[j];
if (sum%2==0){
int len=n-i;
maxim=max(maxim,len);
}
}
}
cout<<maxim;
return 0;
}
I think there is a bug with this original line " int len=n-i " in the second for loop because you miscalculate the len here.
Maybe, you should calculate the len with this new formula " int len= j - i + 1 ", which seems to be the accurate len.
#include <iostream>
#include <limits.h>
using namespace std;
int main()
{
int n;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int maxim=INT_MIN;
for(int i=0;i<n;i++)
{
int sum=0;
for(int j=i;j<n;j++)
{
sum+=arr[j];
if (sum%2==0){
int len= j - i + 1; // Calculate len here
maxim=max(maxim,len);
}
}
}
cout<<maxim;
return 0;
}
Note : Your algorithm above has the time complexity of O(n^2). There are definitely other better algorithms that have the time complexity of O(n) to solve this problem.
First check if the total sum of the array is even. If the total sum of the array is even then the answer will be N.
If the total sum of the array is not even, means it is ODD. So, the idea is to find an odd element from the array such that excluding that element and comparing the length of both parts of the array we can obtain the max length of the subarray with even sum.
int maxLength(int a[], int n){
int sum = 0, len = 0;
// Check if sum of complete array is even
for (int i = 0; i < n; i++)
sum += a[i];
if (sum % 2 == 0) // total sum is already even
return n;
// Find an index i such the a[i] is odd
// and compare length of both halfs excluding
// a[i] to find max length subarray
for (int i = 0; i < n; i++) {
if (a[i] % 2 == 1)
len = max(len, max(n - i - 1, i));
}
return len;
}

Find the largest element of an array in c++

there is an array containing elements from 1 to 10 and any of the element can be repeat you have to find the index of the largest element.
if there is more than 2 similar largest elements then show the smallest index of those elements.
like [2,2,1,0,0]
then you will print 0.
#include<bits/stdc++.h>
using namespace std;
int main()
{
while(1){
int n;
cin>>n;
multimap<int, int> m;
int num;
for(int i=1; i<=n; i++)
{
cin>>num;
m.insert({num,i});
}
int capacity = 5;
int arr[capacity];
for(int i=0; i<capacity; i++){
arr[i] = m.count(i+1);
cout<<i<<" is :\t"<<arr[i]<<"times\n";
}
int a;
a = max_element(arr,arr+capacity)-arr;//it was my doubt section
cout<<a+1;
}
}

function to double size of array arbitrary number of times?

I am trying to get this function to create anew array to be 2x the size of the array argument, copy the contents into the new array, and for the second half of the array, create new values by doing 2*the values in the first half of the array, then delete the original array. Repeat this process for the specified number of times, then return the new array. I feel like I have the right algorithm down but my code isn't working. Please help!
int *ArrayDynamicAllocation(int array[], int size, int number)
{
int *new_array = NULL;
for(int i=0; i<number-1; i++)
{
new_array = new int[size*2];
for(int j=0; j<size-1; j++)
{
new_array[j]=array[j];
new_array[j+size]=2*array[j];
}
array=new_array;
delete[] array;
size=size*2;
}
return new_array;
}
An example output would be if my info to put into my function was
int arr[2] = {0,1};
array_size = 2;
number = 3;
I want it to output 0 1 0 2 0 2 0 4 0 2 0 4 0 4 0 8
int *ArrayDynamicAllocation(int array[], int size, int number)
{
int *new_array = NULL;
int *tmp_array = new int[array.length()];
for(int k=0; k<array.length(); k++)//Initial array copying.
tmp_array[k] = array[k];
for(int i=0; i<number; i++)//Array range 0 to n-1
{
new_array = new int[size*2];
for(int j=0; j<size; j++)//Array range 0 to n-1
{
new_array[j]=tmp_array[j];
new_array[j+size]=2*tmp_array[j];
}
delete[] tmp_array //Deleting old array
size=size*2;
tmp_array = new int[size] //Allocating memory for next iteration
for(int k=0; k<size; k++)
tmp_array[k] = new_array[k];//Copying array for next iteration
}
delete[] tmp_array;// To free memory
return new_array;
};
c array range from 0 to size-1
change
for(int i=0; i<number-1; i++)
to
for(int i=0; i<=number-1; i++)
change
for(int j=0; j<size-1; j++)
to
for(int j=0; j<=size-1; j++)
you are deleting wrong array
change
array=new_array;
delete[] array;
to
delete[] array;
array=new_array;
template<class T>
void changeSize1d(T*&a, const int oldSize, const int newSize){
if(newSize<0)return 0;
T*temp new T[newSize];
int number = min(oldSize, newSize);
copy(a, a+number, temp);
delete [] a;
a = temp;
}

Using Recursion/Backtracking to create and solve a sudoku puzzle

For my computer class, my teacher wants us to use recursion or backtracking to create and solve an nXn size sudoku puzzle. The puzzle has to be dynamically allocated and the only rules for the puzzle is that there can be no repetition in any rows or columns. Diagonals and smaller sub-squares can have repeats. Here is what I have written so far.
#include<iostream>
#include<time.h>
#include<stdlib.h>
#include<stdio.h>
using namespace std;
void fill_puzzle(int **array, int size);
void delete_puzzle(int array, int size);
bool check_filled(int **array, int size);
bool check_correct(int **array, int size){
int temp=0;
for(int i=0; i<size; i++){
for (int j=0; j<size; j++){
for (int k=0;k<size;k++){
if (array[i][k]==array[i][j])
return false;
else
return true;
}
}
}
}
void fill_puzzle(int **array, int size){
srand(time(NULL));
int random_number;
random_number=(rand()%size);
while(check_correct(array,size)==false)
for(int i=0; i<size; i++){
for (int j=0; j<size; j++){
array[i][j]=random_number;
if (check_correct(array, size) ==false)
fill_puzzle(array, size);
else
cout << array[i][j];
}
}
}
void delete_puzzle(int **array, int size){
for (int i=0; i<size; i++){
delete [] array[i];
}
delete []array;
}
int main(){
int size=0;
int **array;
cout << "Hello, what size puzzle would you like to create? Please type 1 number. Example: 3 would make a 3x3 sudoku puzzle."<<endl;
cin >> size;
if (size <= 0){
cout << "The size you have chosen will not work, please choose a number greater than 0." << endl;
cin >> size;
for (int i=0; i<size; i++){
array=new int*[size];
array[size]=new int [size];
}
}
else {
for (int i=0; i<size; i++){
array=new int*[size];
array[size]=new int [size];
}
fill_puzzle(array,size);
delete_puzzle(array, size);
}
return 0;
}
When I try to compile, I get a segmentation error, and using GDB it says that the error occurs in check_correct in the line with if (array[i][k]==array[i][j]). Thanks in advance.
As I can see so far, the code for allocating memory for the 2D array is not correct and the segmentation fault is caused by accessing illegal memory since you didn't allocate properly.
for (int i=0; i<size; i++){
array=new int*[size]; // move it out of loop
array[size]=new int [size]; //array[size]?!
try this:
array = new int*[size];
for(int i = 0; i < size; ++i)
array[i] = new int[size];
There are others problems(fill_puzzle() stuck in an infinite recursion, it leads your stack grow bigger and bigger, until you get a segmentation fault) in your sudoku solver, use a debugger to solve it.

Given an array of integers A(20). Put Min element in the beginning of the array

Task is: Given an array of 20 integers A(20). Find the min positive integer in it and put it in the beginning of the array. Show the initial and changed arrays.
My code is (it works now):
#include <iostream>
using namespace std;
int main(){
int arrayA[20]={6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
int min=arrayA[0];
int i, minplace;
//array's showing in the screen
cout<<"Array A: \n";
for(i=0; i<20; i++)
cout<<arrayA[i]<<" ";
cout<<endl;
//min value of array's element
for(int i=0; i<20; i++)
if (arrayA[i]<min)
{
min=arrayA[i];
minplace=i;
}
cout<<"Min element's value of the array A: "<<min<<endl;
//array 2
int arrayB[21]={min,6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
//array's showing in the screen
cout<<"Array B: \n";
for(i=0; i<21; i++)
cout<<arrayB[i]<<" ";
cout<<endl;
int k=minplace+1;
int n=21;
for (int i=minplace+1; i<n; i++)
arrayB[i]=arrayB[i+1];
n=n-1;
cout<<"Array with deleted element: "<<endl;
for (int i=0; i<n; i++)
cout<<arrayB[i]<<" ";
return 0;
}
THIS CODE WORKS NOW.
This is a very vague question but I did notice that while you are using the variable X, you are never assigning it to anything.
This is a much better approach of doing this which utilizes only a single array and is more precise and clean. Hope that this might help someone in learning.
#include <iostream>
using namespace std;
int main(){
int arrSize = 20;
int myArray[20] = {6,7,8,9,10,11,12,1,2,3,4,5,13,14,15,16,17,18,19,20};
cout<<"Initial Array:\t";
/* loop for printing the initial array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i]<< " ";
/* assuming the first element of the array is the minimum */
int minIndex = 0;
int min = myArray[minIndex];
/* loop for finding the minimum value */
for(int i = 0; i<arrSize; i++){
/* condition for checking if the current element is the minimum */
if(myArray[i]<min){
min = myArray[i];
minIndex = i;
}
}
/* swaping the first element of the array with the minimum element */
myArray[minIndex] = myArray[0];
myArray[0] = min;
cout<<"\nFinal Array:\t";
/* loop for printing the final array */
for(int i = 0; i<arrSize; i++)
cout<< myArray[i] << " ";
return 0;
}