Sort an array A using Quick Sort. Using reccursion - quicksort

#include<iostream>
using namespace std;
void quickSort(int input[], int start, int end)
{
// your code goes here
}
void quickSort(int input[], int size)
{
quickSort(input, 0, size - 1);
}
*/
void swap(int* a,int* b){
int temp=*a;
*a=*b;
*b=temp;
}
int count(int input[],int start,int end ){
static int c=0;
if(start==end)
return c;
if(input[start]>input[end])
c++;
return count(input,start,end-1);
}
int partionArray(int input[],int start,int end ){
int c=count(input,start,end);
int pi=c+start;
swap(&input[start],&input[pi]);
int i=start;
int j=end;
while(i<pi&&j>pi)
{
if(input[i]<input[pi])
{
i++;
}
else if(input[j]>=input[pi])
{
j--;
}
else
{
swap(&input[i],&input[j]);
i++;
j--;
}
}
return pi;
}
void qs(int input[],int start, int end){
if(start>=end)
return;
int pi=partionArray(input,start,end);
qs(input,start,pi-1);
qs(input,pi+1,end);
}
void quickSort(int input[], int size) {
qs(input,0,size-1);
}
int main(){
int n;
cin >> n;
int *input = new int[n];
for(int i = 0; i < n; i++) {
cin >> input[i];
}
quickSort(input, n);
for(int i = 0; i < n; i++) {
cout << input[i] << " ";
}
delete [] input;
}
Sort an array A using Quick Sort. Using reccursion is the question.
Input format :
Line 1 : Integer n i.e. Array size
Line 2 : Array elements (separated by space)
Output format :
Array elements in increasing order (separated by space)
Constraints :
1 <= n <= 10^3
What did i do wrong in this code pls can any one explain?Is every thing right with this code?

Related

Backtrack the difference between these two codes

I have been trying to play around with backtracking. From my understanding these two codes are doing same thing but somehow I got different outcomes.
I am just trying to use some type of template to start with.
cout<<i<<endl;
backtrack(i+1);
backtrack(i+1);
and
for(int i=start; i<n; i++){
cout<<i<<endl;
backtrack(i+1);
}
The first one gets 5 as outcome and the second one gets six when I have the input of
nums=[1,1,1,1,1]
target = 3
public class Solution {
int count = 0;
public int findTargetSumWays(int[] nums, int S) {
calculate(nums, 0, 0, S);
return count;
}
public void calculate(int[] nums, int i, int sum, int S) {
if (i == nums.length) {
if (sum == S) {
count++;
}
} else {
calculate(nums, i + 1, sum + nums[i], S);
calculate(nums, i + 1, sum - nums[i], S);
}
}
}
class Solution {
public:
int count;
void backtrack(vector<int>& nums, int target, int start, int sum){
if(start==nums.size()){
if(sum==target){
count++;
}
return;
}
else{
for(int i=start; i<nums.size(); i++){
//sum+=nums[i];
backtrack(nums, target, i+1, sum+nums[i]);
sum-=nums[i];
}
}
}
int findTargetSumWays(vector<int>& nums, int target) {
count=0;
int sum=0;
int total=0;
for(auto x:nums)total+=x;
vector<vector<int>> dp;
backtrack(nums, target, 0, sum);
return count;
}
};

Generic function to print a 2d array of any datatype in C [duplicate]

I need to do this to persist operations on the matrix as well. Does that mean that it needs to be passed by reference?
Will this suffice?
void operate_on_matrix(char matrix[][20]);
C does not really have multi-dimensional arrays, but there are several ways to simulate them. The way to pass such arrays to a function depends on the way used to simulate the multiple dimensions:
1) Use an array of arrays. This can only be used if your array bounds are fully determined at compile time, or if your compiler supports VLA's:
#define ROWS 4
#define COLS 5
void func(int array[ROWS][COLS])
{
int i, j;
for (i=0; i<ROWS; i++)
{
for (j=0; j<COLS; j++)
{
array[i][j] = i*j;
}
}
}
void func_vla(int rows, int cols, int array[rows][cols])
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int x[ROWS][COLS];
func(x);
func_vla(ROWS, COLS, x);
}
2) Use a (dynamically allocated) array of pointers to (dynamically allocated) arrays. This is used mostly when the array bounds are not known until runtime.
void func(int** array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i][j] = i*j;
}
}
}
int main()
{
int rows, cols, i;
int **x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * sizeof *x);
for (i=0; i<rows; i++)
{
x[i] = malloc(cols * sizeof *x[i]);
}
/* use the array */
func(x, rows, cols);
/* deallocate the array */
for (i=0; i<rows; i++)
{
free(x[i]);
}
free(x);
}
3) Use a 1-dimensional array and fixup the indices. This can be used with both statically allocated (fixed-size) and dynamically allocated arrays:
void func(int* array, int rows, int cols)
{
int i, j;
for (i=0; i<rows; i++)
{
for (j=0; j<cols; j++)
{
array[i*cols+j]=i*j;
}
}
}
int main()
{
int rows, cols;
int *x;
/* obtain values for rows & cols */
/* allocate the array */
x = malloc(rows * cols * sizeof *x);
/* use the array */
func(x, rows, cols);
/* deallocate the array */
free(x);
}
4) Use a dynamically allocated VLA. One advantage of this over option 2 is that there is a single memory allocation; another is that less memory is needed because the array of pointers is not required.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
extern void func_vla(int rows, int cols, int array[rows][cols]);
extern void get_rows_cols(int *rows, int *cols);
extern void dump_array(const char *tag, int rows, int cols, int array[rows][cols]);
void func_vla(int rows, int cols, int array[rows][cols])
{
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
array[i][j] = (i + 1) * (j + 1);
}
}
}
int main(void)
{
int rows, cols;
get_rows_cols(&rows, &cols);
int (*array)[cols] = malloc(rows * cols * sizeof(array[0][0]));
/* error check omitted */
func_vla(rows, cols, array);
dump_array("After initialization", rows, cols, array);
free(array);
return 0;
}
void dump_array(const char *tag, int rows, int cols, int array[rows][cols])
{
printf("%s (%dx%d):\n", tag, rows, cols);
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
printf("%4d", array[i][j]);
putchar('\n');
}
}
void get_rows_cols(int *rows, int *cols)
{
srand(time(0)); // Only acceptable because it is called once
*rows = 5 + rand() % 10;
*cols = 3 + rand() % 12;
}
(See srand() — why call it only once?.)
Easiest Way in Passing A Variable-Length 2D Array
Most clean technique for both C & C++ is: pass 2D array like a 1D array, then use as 2D inside the function.
#include <stdio.h>
void func(int row, int col, int* matrix){
int i, j;
for(i=0; i<row; i++){
for(j=0; j<col; j++){
printf("%d ", *(matrix + i*col + j)); // or better: printf("%d ", *matrix++);
}
printf("\n");
}
}
int main(){
int matrix[2][3] = { {0, 1, 2}, {3, 4, 5} };
func(2, 3, matrix[0]);
return 0;
}
Internally, no matter how many dimensions an array has, C/C++ always maintains a 1D array. And so, we can pass any multi-dimensional array like this.
I don't know what you mean by "data dont get lost". Here's how you pass a normal 2D array to a function:
void myfunc(int arr[M][N]) { // M is optional, but N is required
..
}
int main() {
int somearr[M][N];
...
myfunc(somearr);
...
}
2D array:
int sum(int array[][COLS], int rows)
{
}
3D array:
int sum(int array[][B][C], int A)
{
}
4D array:
int sum(int array[][B][C][D], int A)
{
}
and nD array:
int sum(int ar[][B][C][D][E][F].....[N], int A)
{
}

C++ Fix the following code so that it will correctly recursively traverse a directory tree in order to find where a particular file is

I have an assignment as following: Write a program will ask the user how many random numbers to generate. Then it will present a menu which has the options of Display, Average, Median, and Standard Deviation, Regenerate, and Quit. Without the use of a switch statement, or an if statements, or pointers to functions, have the program execute the user's selection from the menu. (Note: Function pointers are not allowed!)
This is what I have so far:
#include <iostream>
#include <cstdlib>
#include <array>
#include <cmath>
#include <stdlib.h>
#include <map>
using namespace std;
template <typename T> class wrapperclass
{
public:
static T myclass;
};
class Display
{
public:
static void myFunction(int random[], int num)
{
for(int i=0; i<num; ++i)
{
cout << random[i] <<endl;
}
}
};
class Average
{
public:
static double myFunction(int random[], int num)
{
double avg = 0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
return avg/num;
}
};
class Median
{
public:
static double myFunction(int random[], int num)
{
double mid = 0;
if(num % 2 == 0)
{
mid = (random[num/2] + random[num/2-1])/2;
}
else
{
mid = random[num/2];
}
return mid;
}
};
class StdDi
{
public:
static double myFunction(int random[], int num)
{
double avg=0;
double total=0;
for(int i=0; i<num; ++i)
{
avg += random[i];
}
avg = avg/num;
for(int i=0; i<num; ++i)
{
total += (avg-random[i])*(avg-random[i]);
}
total = total/num;
return sqrt(total);
}
};
class renerate
{
public:
static void myFunction(int)
{
}
};
class quit
{
public:
static void myFunction()
{
exit(EXIT_FAILURE);
}
};
int main()
{
int num = 0;
int option = 0;
map<int, class T> magic;
cout << "How many random numbers would u like to generate? " << endl;
cin >> num;
int random[num];
for(int i=0; i<num; ++i)
{
random[i] = rand() % 100 + 1;
}
cout << " Menu"<<endl
<< "1. Display"<<endl
<< "2. Average"<<endl
<< "3. Median"<<endl
<< "4. Standard Deviation"<<endl
<< "5. Renerate"<<endl
<< "6. Quit"<<endl;
cin >> option;
cout<<wrapperclass<Average>::myclass.myFunction(random, num);
return 0;
}
I'm about to directly pass the user input "option" into that "wrapperclass" like this "wrapperclass" so I can simply call the .myFunction since all classes have the same function name. but this won't work for c++ so is there any work around?

issue in my if statement to make comparison in my java program

any help please, so i already wrote the prog but my if statement in my for loop is not working. the prog need to generate 6 random nos,then apply bubble sort which i already did.then the user must enter 6 numbers and these numbers must be compared against the random numbers and must say whether numbers are found in the random numbers or not. here's the code. something is wrong with the if statement ` public static void main(String[] args) {
try {
int numbers[] = new int[6]; //random numbers will be stored in new array
//2 loop will be created to avoid duplication of numbers
System.out.println("Array before Bubble sort");
for (int i = 0; i < 6; i++) {
numbers[i] = (int) (Math.random() * 40);
if (i > 0) {
for (int b = 0; b < i; b++) { //
if (numbers[b] == numbers[i]) {
i--; //decrement to continue the for loop if the integer has been repeated
}
}
}
System.out.print(numbers[i] + ","); //random numbers will be printed before using sorting bubble sort
}
//sort an array using bubble sort
bubbleSort(numbers);
System.out.println(" \nArray after bubble sort");
for (int i = 0; i < 6; i++) {
System.out.print(numbers[i] + ",");
}
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
System.out.println("\ninput 6 number between 1 and 40");
int inputNumber = Integer.parseInt(input.readLine());
for (int b = 0; b < 6; b++) {
System.out.println("number:");
int outcome=Integer.parseInt(input.readLine());
if(outcome==numbers){
System.out.println("found in random numbers");
}else{
System.out.println("not found in random numbers");
}
}
} catch (Exception e) {
System.out.println("error");
}
}
public static void bubbleSort(int[] numbers) {
int n = numbers.length;
int temp = 0;
for (int i = 0; i < n; i++) {
for (int j = 1; j < (n - i); j++) {
if (numbers[j - 1] > numbers[j]) { //swap the element
temp = numbers[j - 1];
numbers[j - 1] = numbers[j];
numbers[j] = temp;
}
}
}
}
}`
System.out.println("\ninput 6 number between 1 and 40");
//Scanner is specifically designed for getting an input purpose and introduced in Java 5,so better use it
Scanner s = new Scanner(System.in);
//you need to have nested loop here
//But the best way to search is use binary search,as you have already sorted the array
while (s.hasNextInt()) {
//one at a time from the input is put to outcome
int outcome = s.nextInt();
boolean found = false;
for (int b = 0; b < 6; b++) {
found = false;
if (outcome == numbers[b]) {
found = true;
//remember to break the inner loop if a match is found
break;
} else {
found = false;
}
}
if (found == true) {
System.out.println("found in random numbers");
} else {
System.out.println("not found in random numbers");
}

Creating a Linked list with Structs - C++

I was writing a program which could read an input file and store the read data in nodes linked by a "link list". However, I was getting a few errors:
In constructor List::List(), no match for 'operator =' in *((List*)this)->List::list[0] = 0
In constructor Polynomial::Polynomial(): no match for 'operator =' in *((Polynomial*)this)->Polynomial::poly = (operator new(400u), (<statement>), ...)
I have a feeling where I do: I try to access a certain node through an array is where I go wrong, however, I can't figure it out much.
Here is the code:
#include <iostream>
#include <fstream>
using namespace std;
enum result{success, failure};
struct Node
{
double coefficient;
int power;
Node();
Node(double coef, int pwr);
};
struct List
{
Node *list[100];
//Default constructor
List();
};
Node::Node()
{
coefficient = 0;
power = 0;
}
List::List()
{
*list[0] = NULL;
}
Node::Node(double coef, int pwr)
{
coefficient = coef;
power = pwr;
}
class Polynomial
{
public:
Polynomial();
result multiply(Polynomial &p, Polynomial &q);
result add(Polynomial p, Polynomial &q);
void initialize(ifstream &file);
void simplify(Polynomial &var);
void print_poly();
~Polynomial();
private:
List *poly; //Store the pointer links in an array
Node first_node;
int val;
};
Polynomial::Polynomial()
{
*poly = new List();
}
Polynomial::void initialize(ifstream &file)
{
int y[20];
double x[20];
int i = 0, j = 0;
//Read from the file
file >> x[j];
file >> y[j];
first_node(x[j], y[j++]); //Create the first node with coef, and pwr
*poly->list[i] = &first_node; //Link to the fist node
//Creat a linked list
while(y[j] != 0)
{
file >> x[j];
file >> y[j];
*poly->list[++i] = new Node(x[j], y[j++]);
}
val = i+1; //Keeps track of the number of nodes
}
Polynomail::result multiply(Polynomial &p, Polynomial &q)
{
int i, j, k = 0;
for(i = 0; i < p.val; i++)
{
for(j = 0; j < q.val; j++)
{
*poly->list[k] = new Node(0, 0);
*poly->list[k].coefficient = (p.poly->list[i].coefficient)*(q.poly->list[j].coefficient);
*poly->list[k++].power = (p.poly->list[i].power)+(q.poly->list[j].power);
}
}
val = k+1; //Store the nunber of nodes
return success;
}
Polynomial::void simplify(Polynomial &var)
{
int i, j, k = 0;
//Create a copy of the polynomial
for(j = 0; j < var.val; j++)
{
*poly->list[j] = new Node(0, 0);
*poly->list[j].coefficient = var.poly->list[j].coefficient;
*poly->list[j].power = var.poly->list[j].power;
}
//Iterate through the nodes to find entries which have the same power and add them, otherwise do nothing
for(k = 0; k < var.val; k++)
{
for(i = k; i < var.val;)
{
if(*poly->list[k].power == var.poly->list[++i].power)
{
if(*poly->list.power[0] == 0)
{
NULL;
}
else
{
*poly->list[k].coefficient = *poly->list[k].coefficient + var.poly->list[i].ceofficient;
var.poly->list[i] = Node(0, 0);
}
}
}
}
}
Polynomial::void print_pol()
{
int i = 0;
for(i = 0; i < temp.val; i++)
{
cout << "Coefficient: " << temp.poly->list[i].coefficient << ", and " << "Power: " << temp.poly->list[i].power << endl;
}
}
The problem is a wrong dereference. Line 34 should probably be
list[0] = NULL; // remove the *
You try to assign the value NULL to a variable of the type Node, but you probably mean a pointer to Node.
The very same is true in line 63.
In addition, line 66 sould probably b:
void Polynomial::initialize(ifstream &file) // start with return type