How to insert an element in order given an array? - c

Let us assume we have the following numbers in an array: 1, 3, 6, 15
If the user inputs a certain integer such as the number 5, than how could you have it inserted in the correct order in the above array so that you could print the following new array:
1, 3, 5, 6, 15. The array to be used is a variable length array and we are assuming that the user enters the numbers of the array in a sorted and non-decreasing order, so there is no need for sorting but just to insert an element (also entered by user) in the correct place. Below I have the code as to how far I got because I don't know what command to use to do the insertion of x into the array, and I am a newbie to C programming.
#include <stdio.h>
int insertion_array (int n, int ary[*]);
int main (void)
{
int n; // size
int x; // The element to be inserted in the array
int i, j;
printf("Enter size of array: ");
scanf("%d", &n);
printf("Enter the value of x: ");
scanf("%d", &x);
int ary[n];
for(i = 0; i < n; i++)
{
printf("Enter number %d: ", i + 1);
scanf("%d", &ary[i]);
} // for
return 0;
} // main

I could come up with a simple O(n) algorithm:
use binary search to find the place to insert, say position 5
shift all numbers after position 5 right
assign position 5 to the new integer
But there are O(lgn) algorithm for insertion, say AVL-tree, RB-tree and etc. But are much more complicated.
#include <stdio.h>
#include <stdlib.h>
int binsearch(int *arr, int size, int key)
{
int low = 0, high = size - 1;
if (key > arr[high]) return size;
while (high > low) {
int mid = (low + high) / 2;
if (arr[mid] > key) high = mid;
else low = mid + 1;
}
return low;
}
int main()
{
int size = 10;
int *arr = (int *)malloc(size * sizeof(int));
int elem, len = 0;
arr[len++] = 0;
while (scanf("%d", &elem) != EOF) {
int pos = binsearch(arr, len, elem);
printf("%d\n", pos);
int i;
for (i = len-1; i >= pos; --i)
arr[i+1] = arr[i];
arr[pos] = elem;
++len;
for (i = 0; i < len; ++i)
printf("%d ", arr[i]);
printf("\n");
}
free(arr);
return 0;
}

Related

Insertion Sort Algorithm

I am reading Cormen Introduction To Algorithms book and i'm trying to translate the pseudocode of Insertion Sort example into real C code.
The problem is that the algorithm i wrote seems not working and i cannot understand why; for instance when i insert something like: {4, 3, 2, 1} the output still be the same and when i insert something like {8, 9, 1, 12, 3} the output become {8, 9, 1, 12, 3} which doesn't make any sense.
Someone can find what i did wrong?
This is the code i wrote:
#include <stdio.h>
void insertionSort(int *Arr, unsigned int size);
int main(void) {
//The size of the array
unsigned int size = 0;
printf("Insert how many elements you want to sort(min 2): ");
scanf_s("%d", &size);
//Check if the value are higher than 1
while (size < 2) {
printf("\nPlease, choose a higher value: ");
scanf_s("%d", &size);
}
//Let's define the array with the choosen size
//The array is allocated dynamically on the heap of the memory
int *Arr;
Arr = calloc(size, sizeof(int));
//Ask the elements
printf("Insert %d elements:\n", size);
for (int i = 0; i < size; i++) {
printf("Insert the %d element: ", i+1);
scanf_s("%d", &Arr[i]);
}
//Print the result
printf("Sorted array: \n");
for (int i = 0; i < size; i++)
printf("%d\n", Arr[i]);
free(Arr);
return 0;
}
void insertionSort(int *Arr, unsigned int size) {
for (int j = 1; j < size; j++) { //Start with the 2nd element of the array
int key = Arr[j]; //the current element of A[j] is stored in key
int i = j;
while ((i >= 1) && (Arr[i - 1] > key)) {
Arr[i] = Arr[i - 1];
i--;
}
Arr[i] = key; //at position I(decreased by 1) is stored Key.
}
}
You are not calling the insertionSort function. Just adding:
for (int i = 0; i < size; i++) {
printf("Insert the %d element: ", i+1);
scanf_s("%d", &Arr[i]);
}
insertionSort(Arr, size);
//Print the result
printf("Sorted array: \n");
Made it work for me.
Note that you alse have to include stdlib.h for calloc.

Swapping largest and smallest numbers in 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;
}

How do I shift an array in C? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
so I am trying to do a couple of things. First I want to shift the array based on the user input. So let's say the user enters (in this order): 1, 2, 3, 4, 5. I want to shift it so that it becomes 2, 3, 4, 5, 1.
As you can see, this particular array is scalable, i.e the dimensions aren't fixed.
#include <stdio.h>
void arrayShift(int *a, int intLength);
int main() {
int arr[10] = {0}; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++) {
scanf("%d", arr+i);
}
return 0;
}
Then I want to print out the and then create a function that multiplies each number by the one before it (after shifting it): so using the same numbers as before (2, 3, 4, 5, 1), we should get an output of 2, 6, 12, 20, 5.
It seems this could be done simply. For the described 'rotation' we can just copy the first element to after the last, change the starting index and call it rotated without moving all the data. And other simplifications:
#include <stdio.h>
int main() {
int number_elements;
printf("Enter the size of the array (MAX): ");
(void) scanf("%d", &number_elements); // should test return value in case of bad input
int array[number_elements + 1]; // array for input numbers (over allocate by 1 for rotation)
printf("Now please enter your %d values:\n", number_elements);
for (int i = 0; i < number_elements; i++)
{
(void) scanf("%d", array + i); // ditto re return value
}
array[number_elements] = array[0]; // rotated array now starts at 1
for (int i = 1; i <= number_elements; i++)
{
printf("%d ", array[i]); // print the rotated array
array[i - 1] *= array[i]; // multiply the rotated array
}
putchar('\n');
for (int i = 0; i < number_elements; i++) // multiplied array starts at 0 again
{
printf("%d ", array[i]); // printing the multiplied, rotated array
}
putchar('\n');
return 0;
}
USAGE
% ./a.out
Enter the size of the array (MAX): 5
Now please enter your 5 values:
1 2 3 4 5
2 3 4 5 1
2 6 12 20 5
%
I'm not sure your text and your example agree with one another so this is my assumption of what you want but it can be tweaked as needed.
Hope this helps..
#include <stdio.h>
void arrayRotate(int a[], int intLength)
{
int temp = a[0],t,i; // storing the first element in a temporary variable
for(i=1;i<intLength;i++)
a[i-1] = a[i]; // Left shifting the elements starting from index 1
a[i-1] = temp; // In the last the first index element is restored back
}
void multArr(int a[],int b[],int n)
{
int i;
b[0] = a[0]; // copying the value at index 0 to the new array
for(i=1;i<n;i++)
{
b[i] = a[i]*a[i-1]; // performing the multiplication on the new array
} // referencing the values from the old array
}
int main() {
int arr[10] = {0}, cpy[10]; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++)
{
scanf("%d", arr+i);
}
arrayRotate(arr,array); // calling function for rotating
multArr(arr,cpy,array); // calling function for the multiplication stuff
for (i = 0; i < array; i++) // printing the rotated array
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i < array; i++) // printing the multiplied array
{
printf("%d ", cpy[i]);
}
return 0;
}
Alright so here's what I've got so far. It's kind of working but it's also not. Specifically, the problem is when I run it, it prints 6, 12, 20, 5 1, and not 2, 6, 12, 20, 5 (this is assuming the numbers of the array are 1, 2, 3, 4, 5)
#include <stdio.h>
void shift (int arr[], int num);
void multiply (int arr[], int num);
int main() {
int arr[10] = {0}; //array for input numbers
int array = 0;
printf("Enter the size of the array (MAX): ");
scanf("%d", &array);
printf("Now please enter your %d values: \n", array);
int i;
for (i = 0; i < array; i++) {
scanf("%d", arr+i);
}
shift(arr, array);
return 0;
}
//shift function
void shift (int arr[], int num) {
int tempVar; //temporary variable
int i;
tempVar = arr[0]; //setting the temporary variable to the first element of a
for (i = 0; i < num -1; i++) {
arr[i] = arr[i +1];
printf(" %d ", arr[i]);
arr[i -1] *= arr[i];
} //arr[0] = tempVar * arr[0];
arr[i] = tempVar; //i < num, print(arr[i])
printf("%d \n", arr[i]);
for ( int i = 0; i < num; i++) {
printf(" %d ", arr[i]);
}
printf("\n");
}

Sorting array based on index of minimum value?

I'm currently trying to learn C, and the exercise I found online has me creating a function that returns the index of the smallest value in an array. This is my function:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = 0;
for (int index = i; index < j; index++){
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
i and j are the lower and upper bound numbers the function should look in. For example, if i is 4 and j is 8, that means the function will return the index of the smallest value between indices 4 and 8.
Here is my main function:
#include <stdio.h>
int main(){
int numbers[10];
int user_input = 0;
for (int i = 0; i < 10; i++){
printf("Please enter a number: ");
scanf_s("%d", &user_input);
numbers[i] = user_input;
}
for (int i = 0; i < 10; i++){
int index_of_min_value = return_index_of_minimum(numbers, i, 10);
int old_num = numbers[index_of_min_value];
int new_num = numbers[i];
numbers[index_of_min_value] = new_num;
new_array[i] = old_num;
}
for (int i = 0; i < 10; i++){
printf("%d\n", new_array[i]);
}
}
The user would first enter a bunch of numbers and that would populate the array with the user's values. The idea is to use return_index_of_minimum to return the index of the smallest item in an array, and then set that equal to numbers[0] with a for loop, and then numbers[1], and then so on. old_num is the lowest number in the array, at its previous index. Here, I'm trying to swap that minimum value with whatever is at numbers[i] However, when I'm done sorting through the entire array, and am printing it out, I see that 10 (when the user enters 1-10 randomly for values) is at index 0, and then the rest of the numbers are in order. Does anybody see what is wrong here?
Here is a fix:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = i;
...
}
Unfortunately this code doesn't have protection of invalid arguments, but otherwise this is an answer you've been looking for.
The reason is in call index_of_minimum(a, 9, 10): the loop performs only one iteration for index = 9, and because the minimum value is already initialized to value a[9], the index_to_return is not updated due to condition check.
This is a different approach that doesn't have same issue:
int return_index_of_minimum(int A[10], int i, int j){
/* assuming i < j */
int minimum_value = A[i];
int index_to_return = i; /* First element is a candidate */
for (int index = i + 1; index < j; index++){
/* Iterate from second element */
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
I believe there is an error in your return_index_of_minimum function.
int index_to_return = 0;
The problem lies I think here as the value of index_to_return will stay 0 if you call return_index_of_minimum(numbers, 5, 10); and that numbers[5] if the actual minimum.
However why not use a simple bubble-sort like the one implemented here
/*
* C program to sort N numbers in ascending order using Bubble sort
* and print both the given and the sorted array
*/
#include <stdio.h>
#define MAXSIZE 10
int main(void)
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}

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