Swapping largest and smallest numbers in C - c

I want to write a program that reads 10 int values from the user and swaps the largest and smallest numbers on the first and second values, then the rest of the numbers should be in the order.
Please check the code and help me what the wrong is.
For instance:
1
9
4
5
6
7
8
2
4
5
New order should be 9 1 4 5 6 7 8 2 4 5
#include <stdio.h>
int main() {
int a[10],i,min,max=0,pos=0;
printf("Please enter 10 int values :\n");
do{
scanf("%d", &a[pos++]);
} while (pos<10);
for (i=0; i<10;i++) {
printf("%i\n",a[i]);
if (max<a[i])
{
max=a[i];
}
if (min>a[i])
{
min=a[i];
}
for (i=0;i<10;i++) {
if (a[i]==max)
a[i]=max;
if (a[i] == min) a[i] = min;
}
printf("The new order is : %d %d %d ", max, min, ...);
return 0;
}
EDIT:
It is the new form
#include <stdio.h>
int main() {
int a[10],i,pos,temp,min = 0,max = 0;
printf("Please enter 10 int values :\n");
do {
scanf("%d", &a[pos++]);
} while (pos < 10);
for ( =1; i<10;i++) {
if (a[i]>a[max])
{
max=i;
}
if (a[i]<a[min])
{
min=i;
}
}
temp=a[max];
a[max]=a[min];
a[min]=temp;
printf("%d %d",a[max],a[min]);
for (i=0;i<10;i++){
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");
return 0;
}

As others have noted, your code does not properly identify the maximum and minimum values in the array because you are writing min and max back into the array instead of the other way around.
Since you want to swap these values, what you actually want are the indices of the min and max values of the array, and swap those.
It is best to break this code into functions instead of having everything in main. Here is a solution that will do what you want:
#include <stdio.h>
int indexofmax(int *data, int len)
{
int max = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]>data[max]) max = i;
}
return max;
}
int indexofmin(int *data, int len)
{
int min = 0;
int i;
for(i = 0; i < len; i++)
{
if(data[i]<data[min]) min = i;
}
return min;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
int main()
{
// user enters in 10 ints...
int max = indexofmax(a, 10);
int min = indexofmin(a, 10);
int i;
swap(&a[min], &a[max]);
for(i = 0; i < 10; i++)
{
printf("%d ", a[i]);
}
return 0;
}

This initialization min=0,max=0 is not right.
Instead have min = INT_MAX and max = INT_MIN.
By setting min=0, you would never get the lowest number in the array if it is greater than 0.
Similarly by setting max=0, you would never get the greatest number in the array if it is lower than 0.
You are gaining nothing by this code:
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }

It is evident that this loop
for(i=0;i<10;i++)
{ if(a[i]==max) a[i]=max;
if(a[i]==min) a[i]=min; }
does not make sense.
Moreover variable min is not initialized while variable max is initialized incorrectly.
int a[10],i,min,max=0,pos=0;
For example the array can contain all negative elements. In this case you will get incorrect value of the maximum equal to 0.
And I do not see where the elements are moved to the right to place the maximum and the minimum to the first two positions of the array.
If I have understood correctly then what you need is something like the following. To move the elements you could use standard function memmove declared in header <string.h>. However it seems you are learning loops.
#include <stdio.h>
#define N 10
int main( void )
{
int a[N] = { 4, 5, 9, 6, 7, 1, 8, 2, 4, 5 };
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
size_t min = 0;
size_t max = 0;
for (size_t i = 1; i < N; i++)
{
if (a[max] < a[i])
{
max = i;
}
else if (a[i] < a[min])
{
min = i;
}
}
if (max != min)
{
int min_value = a[min];
int max_value = a[max];
size_t j = N;
for (size_t i = N; i != 0; --i)
{
if (i - 1 != min && i - 1 != max)
{
if (i != j)
{
a[j - 1] = a[i - 1];
}
--j;
}
}
a[--j] = min_value;
a[--j] = max_value;
}
for (size_t i = 0; i < N; i++) printf("%d ", a[i]);
printf("\n");
}
The program output is
4 5 9 6 7 1 8 2 4 5
9 1 4 5 6 7 8 2 4 5

You're not actually altering the array.
In the second loop, you say "if the current element is the max, set it to the max". In other words, set it to its current value. Similarly for the min.
What you want is to swap those assignments.
if(a[i]==max) a[i]=min;
if(a[i]==min) a[i]=max;
Also, your initial values for min and max are no good. min is unitialized, so its initial value is undefined. You should initialize min to a very large value, and similarly max should be initialized to a very small (i.e. large negative) value.
A better way to do this would be to keep track of the index of the largest and smallest values. These you can initialize to 0. Then you can check a[i] > a[max] and a[i] < a[min]. Then you print the values at indexes min and max, then loop through the list and print the others.
int i, temp, min=0, max=0;
for (i=1; i<10; i++) {
if (a[i] > a[max]) max = i;
if (a[i] < a[min]) min = i;
}
printf("%d %d ", a[max], a[min]);
for (i=0; i<10; i++) {
if ((i != min) && (i != max)) {
printf("%d ", a[i]);
}
}
printf("\n");

Just keep it nice and simple, like this:
#include <stdio.h>
#include <stdlib.h>
#define MAXNUM 10
int find_biggest(int A[], size_t n);
int find_smallest(int A[], size_t n);
void print_array(int A[], size_t n);
void int_swap(int *a, int *b);
int
main(void) {
int array[MAXNUM], i, smallest, biggest;
printf("Please enter 10 int values:\n");
for (i = 0; i < MAXNUM; i++) {
if (scanf("%d", &array[i]) != 1) {
printf("invalid input\n");
exit(EXIT_FAILURE);
}
}
printf("Before: ");
print_array(array, MAXNUM);
smallest = find_smallest(array, MAXNUM);
biggest = find_biggest(array, MAXNUM);
int_swap(&array[smallest], &array[biggest]);
printf("After: ");
print_array(array, MAXNUM);
return 0;
}
int
find_biggest(int A[], size_t n) {
int biggest, i, idx_loc;
biggest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] > biggest) {
biggest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
int
find_smallest(int A[], size_t n) {
int smallest, i, idx_loc;
smallest = A[0];
idx_loc = 0;
for (i = 1; i < n; i++) {
if (A[i] < smallest) {
smallest = A[i];
idx_loc = i;
}
}
return idx_loc;
}
void
print_array(int A[], size_t n) {
int i;
for (i = 0; i < n; i++) {
printf("%d ", A[i]);
}
printf("\n");
}
void
int_swap(int *a, int *b) {
int temp;
temp = *a;
*a = *b;
*b = temp;
}

Related

Program to find prime numbers from the set of numbers of Fibonacci series in C

I want to find prime numbers from the Fibonacci series after printing them. First, I implemented the code for Fibonacci then added each element into an array. Then passed the array to a method to check for prime. Wanted to try it with an array. Displaying the series but not the prime numbers from the following code.
#include <stdio.h>
int fib()
{
int a=0,b=1, arr[20];
arr[0] = a;
arr[1] = b;
printf("%d, %d,",a, b );
int c=0;
for(int i=2; i<=20; i++)
{
c=a+b;
arr[i] = c;
printf("%d,",c);
a=b;
b=c;
}
checkPrime(arr);
}
void checkPrime(int a[])
{
int i, count;
for(i=0; i<sizeof(a); i++)
{
count=0;
for(int j=2; j<=a[i]/2 ; j++)
{
if(a[i]%2==0)
count++;
}
if(count>1)
printf("%d is a Prime", a[i]);
}
}
int main()
{
fib();
}
Output of the code
0, 1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,1597,2584,4181,6765,
8 is a Prime
You have certain bugs in your implementation.
In fib function you iterate until i <= 20 but your arr have length 20 therefore your loop will go out of bounds of array. You should iterate until i < 20 or increase length of your array.
In checkPrime function you iterate until i < sizeof(a). But sizeof function doesn't return size of your array. It returns size of type of variable that you pass to it therefore it will return sizeof(int*) which = 8 (in case you 64 bit machine but I guess you have). To fix this bug you should pass length of your array in checkPrime function and use it.
You don't reset the count variable after j loop.
checkPrime function doesn't check if the number is prime. You have wrong expression in your nested loop. To check if number N is prime you should check if there any divisor of N that at least less than sqrt(N). Your expression is wrong.
Considering the adjustments above I suggest the next solution:
void checkPrime(int a[], size_t a_len) {
int i, count;
for (i = 1; i < a_len; i++) {
count = 0;
for (int j = 2; j <= sqrt((double)a[i]); j++) {
if (a[i] % j == 0) {
count++;
break;
}
}
if (count == 0) {
printf("%d is a Prime\n", a[i]);
} else {
count = 0;
}
}
}
int fib() {
size_t arr_size = 21;
int a = 0, b = 1, arr[arr_size];
arr[0] = a;
arr[1] = b;
printf("%d, %d, ", a, b);
int c = 0;
for (int i = 2; i < arr_size; i++) {
c = a + b;
arr[i] = c;
if (i == arr_size - 1)
printf("%d ", c);
else
printf("%d, ", c);
a = b;
b = c;
}
printf("\n");
checkPrime(arr, arr_size);
}

Hiding even numbers from display in array in C

Any suggestion on how to hide even numbers from user input and only printing odd numbers in ascending order? Like this output describes:
5
3
2
8
7
OUTPUT:
3
5
7
Press any key to continue . . .
I've been trying to figure it out in few hours but was unable to figure the solution :( .
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
Just add 'if(number[i]%2==0)' in your program.
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
for (j = 0; j < count; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (number[j] > number[k])
{
temp = number[j];
number[j] = number[k];
number[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < count; ++i)
if(number[i]%2!=0)
printf("%d\n", number[i]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
try to use the following code will solve your problem :
#include <stdio.h>
#include <time.h>
void sort(int number[], int count)
{
int temp, i, j, k;
int numbs[100];
int counter = 0;
for(int h=0; h<count; ++h){
if(number[h] % 2 != 0){
numbs[counter] = number[h];
counter++;
}
}
for (j = 0; j < counter; ++j)
{
for (k = j + 1; k < count; ++k)
{
if (numbs[j] > numbs[k])
{
temp = numbs[j];
numbs[j] = numbs[k];
numbs[k] = temp;
}
}
}
printf("OUTPUT:\n");
for (i = 0; i < counter; ++i)
printf("%d\n", numbs[I]);
}
void main()
{
int i, number[1000];
int count = 5;
printf("\nType your number:");
for (i = 0; i < count; ++i)
scanf("%d", &number[i]);
sort(number, count);
}
There are many ways to accomplish the task, the following might be an overkill.
Consider the interface and usage of qsort to sort an array of int in ascending order.
#include <stdlib.h>
// It needs a function that compares the values
int cmp_int(void const *lhs, void const *rhs)
{
int const a = *(int *)lhs;
int const b = *(int *)rhs;
return (b < a) - (a < b);
}
int main(void)
{
int a[] = {42, 17, -3, 0, 8, -2, 33};
size_t const a_size = (sizeof a) / (sizeof a[0]);
qsort(a, a_size, // The source array and the number of its elements.
sizeof(a[0]), // The size of each element.
cmp_int); // The pointer to the comparator function.
// ...
}
You can adapt the same concepts and write a function that prints only the odd elements.
#include <stdbool.h>
#include <stdio.h>
bool is_odd(int x)
{
return (x % 2) != 0;
}
void print_if(char const *fmt,
size_t n, int const *a,
bool (*predicate)(int))
{
for (size_t i = 0; i < n; ++i)
{
if ( predicate(a[i]) )
printf(fmt, a[i]);
}
putchar('\n');
}
int main(void)
{
int a[] = //...
size_t const a_size = //...
// ...
// Sort 'a', hopefully using qsort.
print_if("%d ", a_size, a, is_odd);
// ...
}
As an alternative, you could copy only the odd elements into another (suitably sized) array, sort it and print it all.
size_t copy_if(size_t n, int const *src,
int *dst,
bool (*predicate)(int))
{
size_t j = 0;
for ( size_t i = 0; i < n; ++i )
{
if ( predicate( src[i] ) )
{
dst[j] = src[i];
++j;
}
}
return j; // Note that the number of elements copied is returned. Use it!
}
Live example #Compiler Explorer.
For starters according to the C Standard the function main without parameters shall be declared like
int main( void )
As the declared array has 1000 elements then it means that the user may enter any number of values no greater than 1000. Otherwise there is no sense to declare an array with 1000 elements to enter only 5 numbers. That is you should ask the user how many integers he is going to enter.
Your sort function does not distinguish odd and even numbers. It tries to sort all elements of the array though it seems you need to sort only elements with odd values.
To sort only elements with odd values of an array you could use for example the bubble sort algorithm.
Also you should split sorting and outputting elements with odd values in two separate functions.
Here is a demonstration program that shows how the task can be performed.
#include <stdio.h>
void sort_odds( int a[], size_t n )
{
size_t i = 0;
while ( i != n && a[i] % 2 == 0 ) i++;
if ( i != n )
{
a += i;
n -= i;
for ( size_t last = 0; !( n < 2 ); n = last )
{
last = 0;
size_t previous = 0;
for ( size_t j = 0; j < n; j++ )
{
if ( a[j] % 2 == 1 )
{
if ( a[j] < a[previous] )
{
int tmp = a[j];
a[j] = a[previous];
a[previous] = tmp;
last = j;
}
previous = j;
}
}
}
}
}
void display_odds( const int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
if ( a[i] % 2 == 1 ) printf( "%d ", a[i] );
}
putchar( '\n' );
}
int main(void)
{
enum { N = 1000 };
int number[N];
size_t count = 0;
printf( "Enter the number of integers you want to input (no more than %d): ", N );
scanf( "%zu", &count );
if ( count != 0 )
{
if ( N < count ) count = N;
printf( "Enter your integers: " );
int num;
size_t i = 0;
for ( ; scanf( "%d", &num ) == 1 && i < count; i++ )
{
number[i] = num;
}
sort_odds( number, i );
display_odds( number, i );
}
}
The program output might look like
Enter the number of integers you want to input (no more than 1000): 10
Enter your integers: 9 8 7 6 5 4 3 2 1 0
1 3 5 7 9

Sorting an array with duplicate values without modifying the elements, without using secondary array or without using any inbuilt function

So as the question says i am just trying to sort an array with duplicate values.
The array is sorted properly but problem arises when a duplicate value is given to the array
O/P:without duplicate
Enter the size of the array : 5
Enter the 5 elements
7 3 4 8 1
After sorting: 1 3 4 7 8
Original array value 7 3 4 8 1
O/P: with duplicates
5 3 1 1 4
After sorting: 1 3 4 1 3
Original array value 5 3 1 1 4
#include <stdio.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, temp, largest = arr[0], smallest = arr[0];
for( i = 1 ; i < size ; i++ )
{
if(arr[i] > largest)
{
largest = arr[i];
}
if(arr[i] < smallest)
{
smallest = arr[i];
}
}
printf("After sorting: ");
for(i = 0; i < size; i++)
{
temp = largest;
printf("%d ", smallest);
for(k = i + 1; k < size; k++)
{
if(arr[i] == arr[k])
{
smallest = arr[i];
break;
}
for(j = 0; j < size; j++)
{
if(arr[j] > smallest && arr[j] < temp)
{
temp = arr[j];
}
}
smallest = temp;
}
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ", arr[i]);
}
}
int main()
{
int size, i;
printf("Enter the size of the array : ");
scanf("%d", &size);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++)
{
scanf("%d", &arr[i]);
}
print_sort(arr, size);
}
I understand that it is a specific exercise (homework ?), with no possibility to modify the array not to use an additional array.
This implies that classical sorting algorithms cannot work.
Iteratively searching for the minimum is a possible solution, even if not efficient O(n^2).
To cope with duplicates, it it necessary not only to memorize the current minimum, but also its position.
This is a possible implementation.
#include <stdio.h>
#include <stdlib.h>
void print_sort(int *arr, int size) //function definition
{
int i, j, k, largest = arr[0], smallest = arr[0];
int i_smallest = 0;
for (i = 1; i < size; i++ ) {
if (arr[i] > largest) {
largest = arr[i];
}
if(arr[i] < smallest) {
smallest = arr[i];
i_smallest = i;
}
}
printf("After sorting: ");
for (i = 0; i < size; i++) {
int temp = largest + 1;
int i_temp = -1;
printf("%d ", smallest);
if (i == size-1) break;
for (k = 0; k < size; k++) {
if (arr[k] < smallest) continue;
if (arr[k] == smallest) {
if (k <= i_smallest) continue;
i_temp = k;
temp = smallest;
break;
}
if (arr[k] < temp) {
temp = arr[k];
i_temp = k;
}
}
smallest = temp;
i_smallest = i_temp;
}
printf("\n");
printf("Original array value ");
for( i = 0 ; i < size ; i++ )
{
printf("%d ",arr[i]);
}
}
int main(void) {
int size, i;
printf("Enter the size of the array : ");
if (scanf("%d", &size) != 1) exit(1);
int arr[size];
printf("Enter the %d elements\n",size);
for (i = 0; i < size; i++) {
if (scanf("%d", &arr[i]) != 1) exit(1);
}
print_sort(arr, size);
return 0;
}
Maybe it is easier to insert each read value directly into the sorted Array. So you don't have to sort the array afterwards.
If you want to do it this way, geeksforgeeks.org has nice examples also for C which I already used (https://www.geeksforgeeks.org/search-insert-and-delete-in-a-sorted-array/).
// C program to implement insert operation in
// an sorted array.
#include <stdio.h>
// Inserts a key in arr[] of given capacity. n is current
// size of arr[]. This function returns n+1 if insertion
// is successful, else n.
int insertSorted(int arr[], int n, int key, int capacity)
{
// Cannot insert more elements if n is already
// more than or equal to capacity
if (n >= capacity)
return n;
int i;
for (i = n - 1; (i >= 0 && arr[i] > key); i--)
arr[i + 1] = arr[i];
arr[i + 1] = key;
return (n + 1);
}
/* Driver program to test above function */
int main()
{
int arr[20] = { 12, 16, 20, 40, 50, 70 };
int capacity = sizeof(arr) / sizeof(arr[0]);
int n = 6;
int i, key = 26;
printf("\nBefore Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
// Inserting key
n = insertSorted(arr, n, key, capacity);
printf("\nAfter Insertion: ");
for (i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
}

count array value bug

Hi I need help please i need to fix this code so it count the value only once
for exmaple
input:
25
38 25 36 4 1 1 10 37 45 21 37 42 21 1 50 9 50 42 6 39 10 14 17 11 20
10
36 42 2 15 28 42 3 23 8 50
output:
4
the answer here should be 4 not 7.
#include <stdio.h>
int main()
{
int n, m, count = 0;
int array[1000];
int subarray[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d", &subarray[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (array[i] == subarray[j])
count++;
}
}
printf("%d\n", count);
}
Possible solution, using functions and qsort.
(untested code)
#include <stdio.h>
int binarySearch(int arr[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r - l) / 2;
if (arr[mid] == x)
return mid;
if (arr[mid] > x)
return binarySearch(arr, l, mid - 1, x);
return binarySearch(arr, mid + 1, r, x);
}
return -1;
}
int cmpfunc (const void * a, const void * b) {
return (*(int*)a > *(int*)b) - (*(int*)a < *(int*)b);
}
int main() {
int n, m, count = 0;
int array[1000];
int subarray[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++) {
scanf("%d", &array[i]);
}
qsort(array, n, sizeof(int), cmpfunc); // O(n lg n)
scanf("%d", &m);
for (int i = 0; i < m; i++) {
scanf("%d", &subarray[i]);
int result = binarySearch(arr, 0, n - 1, x); // O(lg n)
if (result != -1)
count++;
} // O(m lg n)
printf("%d\n", count);
}
You need to keep track of the matched values in third array as following and
check if the new value is found before or not
#include <stdio.h>
int main()
{
int n, m, count = 0;
int array[1000];
int subarray[1000];
int result[1000];
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
scanf("%d", &array[i]);
}
scanf("%d", &m);
for (int i = 0; i < m; i++)
{
scanf("%d", &subarray[i]);
}
for (int i = 0; i < n; i++)
{
for (int j = 0; j < i; j++)
{
if (array[i] == subarray[j]){
int isFound=0;
for(int k=0;k<count;k++){
if(result[k]==array[i])
isFound=1;
}
if(isFound==0){
result[count]==array[i];
count++;
}
}
}
}
printf("%d\n", count);
}
I use a boolean variable to check if the elements of array 1 exist in the array 2 ,if not ,i will copied it to array 3
#include <stdio.h>
#include <stdbool.h>//header how found the booleen variable
int main()
{
int n,m;
do
{
printf("Give me the length of array 1 :");
scanf("%d",&n);
}while(n<1);
int T1[n];//declaration of Array 1
do
{
printf("Give me the length of array 2 :");
scanf("%d",&m);
}while(m<1);
int T2[m];//declaration of Array 2
printf("The fill of Array 1:\n\n");
for(int i=0;i<n;i++)
{
scanf("%d",&T1[i]);
}
printf("The fill of Array 2:\n\n");
for(int j=0;j<m;j++)
{
scanf("%d",&T2[j]);
}
int T3[n+m];//declaration of Array 3
bool found=false;//declaration of booleen variable
int k=0;
for(int i=0;i<n;i++)
{found=false;
for(int j=0;j<m;j++)
{
if(T1[i]==T2[j])
{
found=true;
}
}
if(found==true)
{
T3[k]=T1[i];
k++;
}
}
printf("\nThe number of elment duplicate is :%d\n",k);
}
so it count the value only once
With minimal impact to OP's code and without re-ordering input:
Check if the subarray[] value already occurred within itself.
When subarray[]/array[] values match, quit looking.
for (int j = 0; j < m; j++) {
bool unique_subarray_value = true;
for (int earlier = 0; earlier < j; earlier++) {
if (subarray[earlier] == subarray[j])
unique_subarray_value = false;
break;
}
}
if (unique_subarray_value) {
for (int i = 0; i < n; i++) {
if (array[i] == subarray[j]) {
count++;
break;
}
}
}
}
A fast approach would sort the arrays and then walk them
// Pseudo code
sort array[n] with qsort()
sort subarray[m] with qsort()
// walk the arrays looking for matches
i = 0;
j = 0;
while (i < n && j < m) {
if (array[i] == subarray[j]) {
count++;
while (i + 1 < n && array[i] == array[i+1]) i++;
while (j + 1 < m && subarray[j] == subarray[j+1]) j++;
}
if (array[i] < subarray[j]) i++;
else j++;
}

Error in function for Selection-Sort

My code for selection-sort
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d",&size);
int b[size],i = 0;
printf("Enter %d integers to be sorted: ",size);
while(i++ < size)
scanf("%d",&b[i]);
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
for(int i = 0; i < size; i++)
printf("%d",b[i]);
return 0;
}
void selection_sort(int a[], int n)
{
while(n >= 0 )
{
if(n == 0)
break;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i++ < n)
if(largest < a[i])
{
c = i ;
largest = a[i];
}
int temp = a[--n];
a[n] = largest;
a[c] = temp;
selection_sort(a, n);
}
}
}
on sorting the array in ascending order
3 4 1 2
is giving weird output
2293388 4 3 0
I checked this many time but failed to remove the problem.
What should I do to work it properly?
Algorithm used :
1. search for largest element in the array.
2. Move largest element to the last position of array.
3. Call itself recursively to sort the first n -1 element of the array.
Please don't give any other solution otherwise I will get confused.
EDIT
Ah, I see what goes wrong. First of all, while (i++ < n) does not do exactly what you expect it to do. It checks if the condition i < n is true, then it increments i. However, it seems that after the conditional check, i is already incremented in the body. So for example,
while (i++ < n)
printf ("%d ", i);
will print out (with n=4):
1 2 3 4
So you first need to change that. Secondly, the outer while-loop is not at all necessary. Using one loop will suffice. Again, change the while loop in here to while (i < n) and increment i in the body. SO the final code will be:
#include <stdio.h>
void selection_sort(int a[], int n);
int main()
{
int size;
printf("Enter the size of array: ");
scanf("%d", &size);
int b[size], i = 0;
printf("Enter %d integers to be sorted: ", size);
while(i < size) {
scanf("%d", &b[i]);
i++;
}
selection_sort(b, size);
printf("Sorted integers(by selection sort) are: ");
i = 0;
for(i = 0; i < size; i++)
printf("%d ", b[i]);
printf ("\n");
return 0;
}
void selection_sort(int a[], int n)
{
if(n == 0)
return;
else
{
int i = 0, c = 0;
int largest = a[0];
while(i < n) {
if(largest < a[i])
{
c = i;
largest = a[i];
}
i++;
}
int temp = a[--n];
a[n] = a[c];
a[c] = temp;
selection_sort(a, n);
}
}
I tested this with your given input (3 4 1 2) and it prints out a sorted list: 1 2 3 4.
Whenever you see such weird big numbers, its usually an array out of bounds issue. Please take a small data-set, say 5-6 numbers, and walk through your program. I am sure you can fix it. Good luck!!

Resources