quick select is not working for all indexes - algorithm

I am trying to implement quick select referring to a algorithm given in the following link
http://www.cs.yale.edu/homes/aspnes/pinewiki/QuickSelect.html
But the program crashes for many k values, and works fine for only few. Kindly guide me where i am doing wrong.
#include <stdio.h>
#include <stdlib.h>
int a1[10];
int a2[10];
int quickselect(int a[], int k,int len){
int r = rand()%(len-1);
int pivot = a[r];
int i =0;
int len1=0,len2=0;
for(i=0 ;i<len;i++){
if(a[i]<pivot)
a1[len1++]=a[i];
else if(a[i]>pivot)
a2[len2++] = a[i];
else
continue;
}
if(k<=len1)
return quickselect(a1, k,len1);
else if (k > len-len2)
return quickselect(a2, k - (len-len2),len2);
return pivot;
}
int main()
{
int a[7] = {8,3,2,6,1,9,5};
int val = quickselect(a,3,7);
printf("%d \n",val);
return 0;
}

I have test your code. I think you should change int r = rand()%(len-1) to int r = rand()%len because when len==1you will get a floating point exception.

Related

Why is my code printing symbols instead of letters?

I am supposed to write a program with three files (mysource.c, myMain.c, and mysource.h) to create a randomly generated string of characters. The length of the string is decided by the user. After the string is generated, the program will bump all letters in the string to the next letter in the alphabet to create a new offset string. I have most of the code sorted out, but my output is printing "╠╠╠╠". It prints the correct amount of characters but it is only printing those symbols. What do I need to do so that the characters print as actual letters rather than these symbols?
Here is my header file:
void generateChars(char *myarr, int len);
void offsetChars(char *myarr, int len);
void printChars(char *myarr, int len);
Here is my source code:
#include <stdio.h>
#include <stdlib.h>
#include "mysource.h"
void generateChars(char* myarr, int len)
{
int i = 0;
char letters[26] ={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o'
,'p','q','r','s','t','u','v','w','x','y','z' };
for (i = 0; i < len; i++);
{
myarr[i] = letters[rand() % 26];
}
}
//end generate function
void offsetChars(char *myarr, int len)
{
char i;
int j;
for (j = 0; j < len; j++)
{
for (i = 'a'; i <= 'z'; i++)
{
if (myarr[j] == i)
{
myarr[j] = i + 1;
break;
}
if (myarr[j] == 'z')
{
myarr[j] = 'a';
break;
}
}
}
}
//end offset function
void printChars(char *myarr, int len)
{
int i;
for (i = 0; i < len; i++)
{
printf("%c",myarr[i]);
}
}//end of print function
Here is my main code:
#include <stdio.h>
#include <stdlib.h>
#include "mysource.h"
int main()
{
int n;
printf("How many random characters do you want to
generate?: ");
scanf_s("%i", &n);
char myarr[1024];
printf("\nOriginal Combo:\n");
generateChars(&myarr, n);
printChars(&myarr, n);
printf("\nOffset Combo:\n");
offsetChars(&myarr, n);
printChars(&myarr, n);
return 0;
}
Here is the output I get:
I don't have enough reputation so this is the picture of the output
Yes there are two source codes, the objective is to make this assignment work with both source codes. Any help is appreciated!

why the constraints reduce the accepted test cases

this is a code i wrote to solve a problem on HackerRank "Recursive Digit Sum"
https://www.hackerrank.com/challenges/recursive-digit-sum
,the code suppose to take two digits as inputs (n,k) to calculate the super digit p.
p is created when k is concatenated n times thats if, k=148 and n=3
p=148148148
sumdigit(P) = sumdigit(148148148)
= sumdigit(1+4+8+1+4+8+1+4+8)
= sumdigit(39)
= sumdigit(3+9)
= sumdigit(12)
= sumdigit(1+2)
= sumdigit(3)
= 3.
the Constraints
1<=n<10^(100000)
1<=k<=10^5
#include <stdio.h>
#include <math.h>
unsigned long int SumDigits(unsigned long int i) {
if (i < 10) {
return i;
}
else {
return i%10 + SumDigits(i/10);
}
}
int main() {
unsigned long int n,k,pos=0;
scanf("%ld %ld",&k,&n);
/**i would put the constraint however it reduces the accepted test cases*/
// if(k>=1&&k<pow(10,100000)&&n>=1&&n<pow(10,5)){
for(unsigned long int i=0;i<n;i++){
pos+=k;
k=k*( unsigned long int)pow(10,n);
}
while(pos>=10){
pos=SumDigits(pos);
}
printf("%ld\n",pos);
//}
return 0;
}

Finding an efficient algorithm

You are developing a smartphone app. You have a list of potential
customers for your app. Each customer has a budget and will buy the app at
your declared price if and only if the price is less than or equal to the
customer's budget.
You want to fix a price so that the revenue you earn from the app is
maximized. Find this maximum possible revenue.
For instance, suppose you have 4 potential customers and their budgets are
30, 20, 53 and 14. In this case, the maximum revenue you can get is 60.
**Input format**
Line 1 : N, the total number of potential customers.
Lines 2 to N+1: Each line has the budget of a potential customer.
**Output format**
The output consists of a single integer, the maximum possible revenue you
can earn from selling your app.
Also, upper bound on N is 5*(10^5) and upper bound on each customer's budget is 10^8.
This is a problem I'm trying to solve . My strategy was to sort the list of budgets and then multiply each of those with its position-index in the sequence - and then print the max of the resulting sequence. However this seems to be quite time-inefficient (at least in the way I'm implementing it - I've attached the code for reference). My upper bound on time is 2 seconds. Can anyone help me find a
more time-efficient algorithm (or possibly a more efficient way to implement my algorithm) ?
Here is my solution :
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
using namespace std;
long long max(long long[],long long);
void quickSortIterative(long long[],long long,long long);
long long partition(long long[],long long,long long);
void swap(long long*,long long*);
int main(){
long long n,k=1;
scanf("%lld",&n);
if(n<1 || n > 5*((long long)pow(10,5))){
exit(0);
}
long long budget[n],aux[n];
for(long long i=0;i<n;i++){
scanf("%lld",&budget[i]);
if(budget[i]<1 || budget[i] > (long long)pow(10,8)){
exit(0);
}
}
quickSortIterative(budget,0,n-1);
for(long long j=n-1;j>=0;j--){
aux[j] = budget[j]*k;
k++;
}
cout<<max(aux,n);
return 0;
}
long long partition (long long arr[], long long l, long long h){
long long x = arr[h];
long long i = (l - 1);
for (long long j = l; j <= h- 1; j++)
{
if (arr[j] <= x)
{
i++;
swap (&arr[i], &arr[j]);
}
}
swap (&arr[i + 1], &arr[h]);
return (i + 1);
}
void swap ( long long* a, long long* b ){
long long t = *a;
*a = *b;
*b = t;
}
void quickSortIterative(long long arr[], long long l, long long h){
long long stack[ h - l + 1 ];
long long top = -1;
stack[ ++top ] = l;
stack[ ++top ] = h;
while ( top >= 0 ){
h = stack[ top-- ];
l = stack[ top-- ];
long long p = partition( arr, l, h );
if ( p-1 > l ){
stack[ ++top ] = l;
stack[ ++top ] = p - 1;
}
if ( p+1 < h ){
stack[ ++top ] = p + 1;
stack[ ++top ] = h;
}
}
}
long long max(long long arr[],long long length){
long long max = arr[0];
for(long long i=1;i<length;i++){
if(arr[i]>max){
max=arr[i];
}
}
return max;
}
Quicksort can take O(n^2) time for certain sequences (often already sorted sequences are bad).
I would recommend you try using a sorting approach with guaranteed O(nlogn) performance (e.g. heapsort or mergesort). Alternatively, you may well find that using the sort routines in the standard library will give better performance than your version.
You might use qsort in C or std::sort in C++, which is most likely faster than your own code.
Also, your "stack" array will cause you trouble if the difference h - l is large.
I have used STL library function sort() of C++. It's time complexity is O(nlogn). Here, you just need to sort the given array and check from maximum value to minimum value for given solution. It is O(n) after sorting.
My code which cleared all the test cases :
#include <algorithm>
#include <stdio.h>
#include <cmath>
#include <iostream>
using namespace std;
int main(){
long long n, a[1000000], max;
int i, j;
cin>>n;
for(i = 0; i < n; i++){
cin>>a[i];
}
sort(a, a + n);
max = a[n - 1];
for(i = n - 2; i >= 0; i--){
//printf("%lld ", a[i]);
if(max < (a[i] * (n - i)))
max = a[i] * (n - i);
}
cout<<max<<endl;
return 0;
}
I dont know if my answer is right or wrong please point out mistakes if there is any
#include<stdio.h>
void main()
{
register int i,j;
long long int n,revenue;
scanf("%Ld",&n);
long long int a[n];
for(i=0;i<n;i++)
scanf("%Ld",&a[i]);
for (i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
a[i]=a[i]+a[j];
a[j]=a[i]-a[j];
a[i]=a[i]-a[j];
}
}
}
for(i=0;i<n;i++)
a[i]=(n-i)*a[i];
revenue=0;
for(i=0;i<n;i++)
{
if(revenue<a[i])
revenue=a[i];
}
printf("%Ld\n",revenue);
}
passed all the test cases
n=int(input())
r=[]
for _ in range(n):
m=int(input())
r.append(m)
m=[]
r.sort()
l=len(r)
for i in range(l):
m.append((l-i)*r[i])
print(max(m))
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main() {
// your code goes here
long long n;
std::cin >> n;
long long a[n];
for(long long i=0;i<n;i++)
{
std::cin >> a[i];
}
sort(a,a+n);
long long max=LONG_MIN,count;
for(long long i=0;i<n;i++)
{
if(a[i]*(n-i)>max)
{
max=a[i]*(n-i);
}
}
std::cout << max << std::endl;
return 0;
}
The following solution is in C programming Language.
The Approach is:
Input the number of customers.
Input the budgets of customers.
Sort the budget.
Assign revenue=0
Iterate through the budget and Multiply the particular budget with the remaining budget values.
If the previous-revenue < new-revenue. assign the new-revenue to revenue variable.
The code is as follows:
#include <stdio.h>
int main(void) {
int i,j,noOfCustomer;
scanf("%d",&noOfCustomer);
long long int budgetOfCustomer[noOfCustomer],maximumRevenue=0;
for(i=0;i<noOfCustomer;i++)
{
scanf("%Ld",&budgetOfCustomer[i]);
}
for(i=0;i<noOfCustomer;i++)
{
for(j=i+1;j<noOfCustomer;j++)
{
if(budgetOfCustomer[i]>budgetOfCustomer[j])
{
budgetOfCustomer[i]=budgetOfCustomer[i] + budgetOfCustomer[j];
budgetOfCustomer[j]=budgetOfCustomer[i] - budgetOfCustomer[j];
budgetOfCustomer[i]=budgetOfCustomer[i] - budgetOfCustomer[j];
}
}
}
for(i=0;i<noOfCustomer;i++)
{
budgetOfCustomer[i]=budgetOfCustomer[i]*(noOfCustomer-i);
}
for(i=0;i<noOfCustomer;i++)
{
if(maximumRevenue<budgetOfCustomer[i])
maximumRevenue=budgetOfCustomer[i];
}
printf("%Ld\n",maximumRevenue);
return 0;
}

Run time comparison of Bubble sort and quick sort

I wish to do a run time comparison of two sorting algorithms- Bubble sot and Randomized Quick sort. My code works fine but I guess I am using some primitive techniques. The 'clock' calculations happen in int, so even if I try to get the time in micro seconds, I get something like 20000.000 micro seconds.
The code:
Bubblesort:
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
int bubblesort(int a[], int n);
int main()
{
int arr[9999], size, i, comparisons;
clock_t start;
clock_t end;
float function_time;
printf("\nBuBBleSort\nEnter number of inputs:");
scanf("%d", &size);
//printf("\nEnter the integers to be sorted\n");
for(i=0;i<size;i++)
arr[i]= rand()%10000;
start = clock();
comparisons= bubblesort(arr, size);
end = clock();
/* Get time in milliseconds */
function_time = (float)(end - start) /(CLOCKS_PER_SEC/1000000.0);
printf("Here is the output:\n");
for(i=0;i<size ;i++)
printf("%d\t",arr[i]);
printf("\nNumber of comparisons are %d\n", comparisons);
printf("\nTime for BuBBle sort is: %f micros\n ", function_time);
return 0;
}
int bubblesort(int a[], int n)
{
bool swapped = false;
int temp=0, counter=0;
for (int j = n-1; j>0; j--)
{
swapped = false;
for (int k = 0; k<j; k++)
{
counter++;
if (a[k+1] < a[k])
{
//swap (a,k,k+1)
temp= a[k];
a[k]= a[k+1];
a[k+1]= temp;
swapped = true;
}
}
if (!swapped)
break;
}
return counter;
}
Sample Output:
BuBBleSort
Enter number of inputs:2000
Time for BuBBle sort is: 20000.000000 micros
Quicksort:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int n, counter=0;
void swap(int *a, int *b)
{
int x;
x = *a;
*a = *b;
*b = x;
}
void quicksort(int s[], int l, int h)
{
int p; /* index of partition */
if ((h- l) > 0)
{
p= partition(s, l, h);
quicksort(s, l, p- 1);
quicksort(s, p+ 1, h);
}
}
int partition(int s[], int l, int h)
{
int i;
int p; /* pivot element index */
int firsthigh; /* divider position for pivot element */
p= l+ (rand())% (h- l+ 1);
swap(&s[p], &s[h]);
firsthigh = l;
for (i = l; i < h; i++)
if(s[i] < s[h])
{
swap(&s[i], &s[firsthigh]);
firsthigh++;
}
swap(&s[h], &s[firsthigh]);
return(firsthigh);
}
int main()
{
int arr[9999],i;
clock_t start;
clock_t end;
float function_time;
printf("\nRandomized Quick Sort");
printf("\nEnter the no. of elements…");
scanf("%d", &n);
//printf("\nEnter the elements one by one…");
for(i=0;i<n;i++)
arr[i]= rand()%10000;
start = clock();
quicksort(arr,0,n-1);
end = clock();
/* Get time in milliseconds */
function_time = (float)(end - start) / (CLOCKS_PER_SEC/1000.0);
printf("\nCounter is %d\n\n", counter);
printf("\nAfter sorting…\n");
for(i=0;i<n;i++)
printf("%d\t",arr[i]);
printf("\nTime for Randomized Quick Sort is: %f ms\n", function_time);
return 0;
}
Sample Output:
Randomized Quick Sort
Enter the no. of elements…9999
Time for Randomized Quick Sort is: 0.000000 ms
As you can see, Quicksort doesn't show any run time with my technique even with a much larger input size than Bubblesort.
Could someone help in refining it with that part of run time comparison?
p.s.: The code is liberally borrowed from online sources
Try the follwoing code.
printf("Clock() %ld", clock());
sleep(1);
printf("\t%ld\n", clock());
my result is...
Clock() 6582 6637
gettimeofday(2) is better than clock(3). Because gettiemofday(2) store time in a struct
struct timeval {
time_t tv_sec; /* seconds */
suseconds_t tv_usec; /* microseconds */
};
Record start time and stop time, then you can get elapsed time in microseconds by the formula
(stop.tv_sec - start.tv_sec) * 1000000. + stop.tv_usec - start.tv_usec

how to reduce page faults in this program?

I'm gating more then 1000 page faults in this program.
can i reduce them to some smaller value or even to zero ?
or even any other changes can speed up the execution
#include <stdio.h>
#include<stdlib.h>
int main(int argc, char* argv[])
{
register unsigned int u, v,i;
register unsigned int arr_size=0;
register unsigned int b_size=0;
register unsigned int c;
register unsigned int *b;
FILE *file;
register unsigned int *arr;
file=fopen(argv[1],"r");
arr=(unsigned int *)malloc(4*10000000);
while(!feof(file)){
++arr_size;
fscanf(file,"%u\n",&arr[arr_size-1]);
}
fclose(file);
b=(unsigned int *)malloc(arr_size*4);
if (arr_size!=0)
{
++b_size;
b[b_size-1]=0;
for (i = 1; i < arr_size; ++i)
{
if (arr[b[b_size-1]] < arr[i])
{
++b_size;
b[b_size-1]=i;
continue;
}
for (u = 0, v = b_size-1; u < v;)
{
c = (u + v) / 2;
if (arr[b[c]] < arr[i]) u=c+1; else v=c;
}
if (arr[i] < arr[b[u]])
{
b[u] = i;
}
if(i>arr_size)break;
}
}
free(arr);
free(b);
printf("%u\n", b_size);
return 0;
}
The line:
arr=(unsigned int *)malloc(4*10000000);
is not a good programming style. Are you sure that your file is as big as 40MBs? try not to allocate the whole memory in the first lines of your program.

Resources