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.
Related
So I need to write a program which takes (by user input) a integer array of 100 elements and finds the max of every 5 elements and writes them in a new array and adds the rest of the numbers to another array.
So an example would be:
original array (array1): 1,23,6,7,16,19,24,56,99,43 ...
soo it will take the first 5 elements: 1,23,6,7,16 and find the max value (23) and add it to the new array
then the next 5 : 19,24,56,99,43 find their max (99) and add it to the other array and so on until it reaches the last number.
second array (array2): 23,99
third array (array3): 1,6,7,16,19,24,56,43
I've tried everything, but i can only get either the Max number in the WHOLE array or the max number of the FIRST 5 elements.
This is how my program should look like:
#include <stdio.h>
#include <stdlib.h>
int array1[100];
int array2[100];
int size;
int main() {
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size > 100) {
return 0;
}
printf("\nEnter %d numbers: \n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array1[i]);
}
printf("\nEntered array: ");
for (int i = 0; i < size; i++) {
printf("%d, ", array1[i]);
}
printf("\n");
// the code for the max numbers should be here
printf("The max values of every 5 elements are: \n");
for(int i = 0; i < size2; i++) {
printf("%d, ", array2[i]);
}
}
"size2" is the size of the new array.
#include <stdio.h>
#include <stdlib.h>
int array1[100];
int array2[100];
int array3[100];
int size, size2, size3;
int main() {
printf("Enter the size of the array: ");
scanf("%d", &size);
if (size > 100) {
return 0;
}
printf("\nEnter %d numbers: \n", size);
for (int i = 0; i < size; i++) {
scanf("%d", &array1[i]);
}
printf("\nEntered array: ");
for (int i = 0; i < size; i++) {
printf("%d", array1[i]);
if(i%5==4) printf("| ");
else printf(", ");
}
printf("\n");
// the code for the max numbers should be here
size2=0; size3=0;
int maxvalue_index=0;
for(int i = 1; i < size; i++) {
if(array1[i]>array1[maxvalue_index]) maxvalue_index=i;
if(i%5==4 || i==size-1){
array2[size2]=array1[maxvalue_index];
size2++;
for(int j=i-(i%5); j<=i ; j++){
if(array1[j]==array1[maxvalue_index]) continue;
array3[size3]=array1[j];
size3++;
}
maxvalue_index=i+1;
}
}
printf("The max values of every 5 elements are: \n");
for(int i=0;i<size2;i++) printf("%d ",array2[i]);
printf("\nArray3\n");
for(int i=0;i<size3;i++) printf("%d ",array3[i]);
printf("\n");
}
Try this, It will work for non 5*n lengths
Let me know if there is any error :)
The function below finds the maximum of elements in the array from start to end exclusive.
int findmax(int *const arr, const size_t len, const size_t begin, size_t end) {
int res = arr[begin];
end = (len < end) ? len : end;
for (int i = begin+1; i < end; i++) {
if (arr[i] > res)
res = arr[i];
}
return res;
}
Define this function before your main, then call it for every five elements; the maximum of the first five elements is findmax(array1, size1, 0, 5), for the next
five it would be findmax(array1, size1, 5, 10) and so on and so forth. It shouldn't take that much effort to make a for loop that automates the process.
I am new to C and I have a problem. I need to reverse the elements of arrays in the following program. Can I get a very simple explanation of what I am doing wrong and how I could go on about fixing it?
Here's the output I get:
Enter number 0: 0
Enter number 1: 1
Enter number 2: 2
Enter number 3: 3
Enter number 4: 4
Enter number 5: 5
Enter number 6: 6
Enter number 7: 7
Element 0 is: 7
Element 1 is: 6
Element 2 is: 5
Element 3 is: 4
Element 4 is: 4
Element 5 is: 5
Element 6 is: 6
Element 7 is: 7
My code:
#include <stdio.h>
void reverse(int a[], int i)
{
int j=7,b;
for (i=0; i<=7; i++)
{
b=a[i];
a[i]=a[j];
a[j]=b;
printf("Element %d is: %d\n", i,a[i]);
j--;
}
}
int main(void)
{
int a[8];
int i;
for(i=0;i<=7;i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
return 0;
}
To avoid being misled, write the output after the reversal, not during it:
#include <stdio.h>
void reverse(int a[], int i)
{
int j = 7, b;
for (i = 0; i <= 7; i++)
{
b = a[i];
a[i] = a[j];
a[j] = b;
j--;
}
}
int main(void)
{
int a[8];
int i;
for (i = 0; i <= 7; i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
for (i = 0; i <= 7; i++)
{
printf("Element %d is: %d\n", i, a[i]);
}
return 0;
}
Now you’ll notice the array isn’t changing at all. That’s because you’re swapping every element in the array twice: once to its reversed position, then back to its original position. To fix this, only loop over the first half the array, i.e. while i < 4.
It was probably also intended to make the second argument to reverse the length, so you should make use of that instead of hard-coding 7 or 4:
void reverse(int a[], int length)
{
int i, j = length - 1, b;
for (i = 0; i < length / 2; i++)
{
b = a[i];
a[i] = a[j];
a[j] = b;
j--;
}
}
You could also copy over the array in a new one:
#include <stdio.h>
void reverse(int a[], int i)
{
int b[i];
int j;
for(j=0; j<i; j++){
b[j] = a[i-1-j];
printf("Element %d is: %d\n", j, b[j]);
}
}
int main(void)
{
int a[8];
int i;
for(i=0;i<=7;i++)
{
printf("Enter number %d: ",i);
scanf("%d", &a[i]);
}
reverse(a, 8);
return 0;
}
What you want to do it move through only half of the length of your array else you're reversing the array twice.
void reverse(int a[], int len)
{
int i;
int j=len-1,b;
for(i=0;i<len/2;i++)
{
b=a[i];
a[i]=a[j];
a[j]=b;
j--;
}
for(i = 0; i < len; i++) {
printf("Element %d is: %d\n", i,a[i]);
}
}
The Principe is simple. just stand at the middle of the table and reverse the elements as follow. so pose n is lent of the table. then the last element is n-1.
so you ave to reverse position t[0] and t[n-2]
reverse t[1] and t[n-3] and so on...
stop when you rich the middle of the table. try to code your self is better than for me giving you the code.
hope it helped.
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");
}
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;
}
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!!