Today I tried to make a program (algorithm) which search into an Array for the next number which is bigger than preview number found and print it.
The number has to be printed only if the next numbers are not smaller.
Fist example: 4,2,3,9,4,6,5: Output should be: 2,3,4,5.
Second example: 2,3,6,4,5,1 The output should be 1.
Third example: 1,9,8,7,6,5 The output should be 1,5.
Example, if array has the following elements 1,4,2,3,6,4,5,8,6 the output should be:
1 2 3 4 5 6
and if array has the following elements 1,4,2,3 the output should be:
1,2,3
Here is the program:
#include <stdio.h>
int sortArr(int* array, int n, int next){
int i,min = array[0];
int lang;
if(next==0){
for (i=0;i<n;i++){
if(array[i]<min){
min=array[i];
}
}
}
if(next != 0){
lang=next;
while(lang==next){
for (i=0;i<n;i++){
if(array[i]<min){
min=array[i];
}
}
lang++;
if(lang== next){
break;
}
}
min=lang;
}
return min;
}
int main(void){
int a[] = {1,4,2,3,6,4,5,8,6};
int i,l = sizeof a / sizeof a[0];
int next = 0;
int min = sortArr(a,l,next);
for(i=0;i<l;i++){
if(min < a[i]){
if(min < a[i]){
min = sortArr(a,l,next);
printf("%d ",min);
}
next++;
}
}
printf("\n");
return 0;
}
I think that, the Output has to do with the fact that the program it is working only if the first element is the smallest from the whole array elements.
EDIT: I tried the following too:
#include <stdio.h>
int sortArr(int* array, int n, int next){
int i,min = array[0];
int lang;
if(next==0){
for (i=0;i<n;i++){
if(array[i]<min){
min=array[i];
}
}
}
if(next != 0){
lang=next;
while(lang==next){
for (i=0;i<n;i++){
if(array[i]<min){
min=array[i];
}
}
lang++;
if(lang== next){
break;
}
}
min=lang;
}
return min;
}
int main(void){
int a[] = {2,1,3,4};
/*int a[] = {9,4,2,3,6,4,5,8,6};*/
int i,l = sizeof a / sizeof a[0];
int next = 0;
int min = sortArr(a,l,next);
for(i=0;i<l;i++){
if(min == a[i]){
continue;
}
if(min < a[i]){
next++;
min = sortArr(a,l,next);
}
printf("%d ",min);
}
printf("\n");
return 0;
}
The output should be 2,3,4 but i get 2,2,3,4.
qsort()?