So that's my task. I don't know how to realize it in 2D.
All variables (i, j, L, R, etc. are integer)
while (L < R)
{
for(i, j = L; i < R; i++, j++)
{
if (a[i][j] > a[i + 1][j + 1])
{
temp = a[i][j];
a[i][j] = a[i + 1][j + 1];
a[i + 1][j + 1] = temp;
k = i;
}
}
R = k;
for(i, j = R - 1; i >= L; i--, j--)
{
if(a[i][j] > a[i + 1][j + 1])
{
temp = a[i][j];
a[i][j] = a[i + 1][j + 1];
a[i + 1][j + 1] = temp;
k = i;
}
}
L = k + 1;
}
I tried this code but I think that something is wrong with that.
Input:
1 10 5
4 0 8
8 18 3
Output: (That should be)
0 10 5
4 1 8
8 18 3
But current Output is
1 10 5
4 0 8
8 18 3
A function to swap values using call by reference.
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
A function implementing shaker sort
void ShakerSort(int a[], int n)
{
int i, j, k;
for(i = 0; i < n;)
{
// First phase for ascending highest value to the highest unsorted index.
for(j = i+1; j < n; j++)
{
if(a[j] < a[j-1])
swap(&a[j], &a[j-1]);
}
// Decrementing highest index.
n--;
// Second phase for descending lowest value to the lowest unsorted index.
for(k = n-1; k > i; k--)
{
if(a[k] < a[k-1])
swap(&a[k], &a[k-1]);
}
// Incrementing lowest index.
i++;
}
}
The main function looks like this
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
ShakerSort(arr, n);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
The above code is written in c++ refer it and make the changes according to your requirment
Related
I was having this problem to which I have come to the solution through the trial and error process but I have no idea why my bubble sort function wasn't working in the first place.
The problem had to do with the for-loops inside my function. Specifically when declaring and defining my i and j variables.
In my version of C I can define variables inside my for-loop parameter, but I can't declare them, so I do both the declaration and definition outside.
Doing so though made my function not work as intended as it didn't sort my array at all.
Though after declaring the variables outside but defining them inside the for-loop parameter to my surprise the function worked properly. My problem is I have no idea why.
Here I am providing both the working version and the non-working version:
Non-Working Version:
void bubbleDesc (int n, int array[])
{
int i = 0, j = 0, temp;
for (i; i < n - 1; i++)
{
for (j; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Working Version:
void bubbleDesc (int n, int array[])
{
int i, j, temp;
for (i = 0; i < n - 1; i++)
{
for (j = 0; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Your not working implementation misses the initialization of j. So it iterates the inner loop only in the first iteration of the outer loop.
void bubbleDesc (int n, int array[])
{
int i = 0, j = 0, temp;
for (i; i < n - 1; i++)
{
j = 0; // this init is needed
for (j; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Thought, better would be to limit the scope of j and declare it only in the block where it is used, i.e., for (int j=0;...){...}
For starters it is better to specify in the function declaration the array as its first parameter and the number of elements in the array as its second parameter.
Also in C sizes of entities are defined as values of the type size_t.
So the function should be declared like
void bubbleDesc( int array[], size_t n );
In your first function implementation the variable j used in the inner for loop is initialized only once before the for loops
void bubbleDesc (int n, int array[])
{
int i = 0, j = 0, temp;
for (i; i < n - 1; i++)
{
for (j; j < n - 1; j++)
//...
though you need to initialize it to 0 each time before the inner for loop will get the control. The second function implementation does such an initialization within the for loop statement.
void bubbleDesc (int n, int array[])
{
int i, j, temp;
for ( i = 0; i < n - 1; i++ )
{
for ( j = 0; j < n - 1; j++ )
//...
Bear in mind that you should declare variables in minimum scopes where they are used. That is it will be better at least to write
void bubbleDesc (int n, int array[])
{
for ( int i = 0; i < n - 1; i++)
{
for (int j = 0; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
}
Or if your compiler does not allow to declare variables in the for loop statement then you can write
void bubbleDesc (int n, int array[])
{
int i = 0;
for ( ; i < n - 1; i++)
{
int j = 0;
for ( ; j < n - 1; j++)
{
if (array[j] < array[j + 1])
{
int temp = array[j + 1];
array[j + 1] = array[j];
array[j] = temp;
}
}
}
But in any case your implementation of the function is not efficient because even when the whole array or its second part is already sorted nevertheless the loops continue its iterations for all elements of the array.
Another drawback is that if you will want to sort the array in the ascending order you will have to write a new function.
You should always try to write more general functions.
It will be better to add to the function a third parameter that will specify a comparison function that will compare elements of array.
Here is a demonstration program that shows how the function can be written.
#include <stdlib.h>
void bubbleSort( int a[], size_t n, int cmp( const void *, const void * ) )
{
for (size_t last = 1; !( n < 2 ); n = last)
{
for (size_t j = last = 1; j < n; j++)
{
if (cmp( a + j, a + j - 1 ) < 0)
{
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
last = j;
}
}
}
}
static int ascending( const void *a, const void *b )
{
int x = *( const int * )a;
int y = *( const int * )b;
return ( y < x ) - ( x < y );
}
static int descending( const void *a, const void *b )
{
int x = *( const int * )a;
int y = *( const int * )b;
return ( x < y ) - ( y < x );
}
int main( void )
{
int a[] = { 9, 2, 6, 5, 8, 1, 3, 7, 4, 0 };
const size_t N = sizeof( a ) / sizeof( *a );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
bubbleSort( a, N, ascending );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
bubbleSort( a, N, descending );
for (size_t i = 0; i < N; i++)
{
printf( "%d ", a[i] );
}
putchar( '\n' );
}
The program output is
9 2 6 5 8 1 3 7 4 0
0 1 2 3 4 5 6 7 8 9
9 8 7 6 5 4 3 2 1 0
I'm new to programming,I'm trying to implement a merge sort function into my program, but it's not working correctly. I went over and over the code but I can't find the problem.
If for example the user input for a 6 element array is : 3 2 4 1 6 7
The output is: 1 3 2 4 32708 32708
Can someone help me? Also, if anyone have any advice for improving my coding style would be much appreciated.Thanks.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int *a, n;
a = malloc(100 * sizeof(int)); // dynamically allocating memory for original array
if (a == NULL)
return 1;
printf("Enter n of elements in the array:");
scanf("%i", &n); // n of elements the in array
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%i", &a[i]); // prompt user for input elements
}
int f, l, m, n1, n2; // declaring variables
f = 0; // first element
l = n - 1; // last element
m = (f + l) / 2; // mid point
n1 = m + 1 - f; // n elements l1
n2 = l - m; // n elements l2
int l1[n1]; // temp array 1
int l2[n2]; // temp array2
for (int i = 0; i < n1; i++) {
l1[i] = a[i]; // copy elements into temp l1
}
for (int j = 0; j < n2; j++) {
l2[j] = a[m + 1 + j]; // copy elements into temp l2
}
int i, j, k; // variable for arrays index
i = 0;
j = 0;
k = 0;
//sorting and copying elements in original array
while (i < n1 && j < n2) {
if (l1[i] <= l2[j]) { // if element l1 smaller or equal to l2 element
a[k] = l1[i]; // copy element l1 into original array
i++; // increment l1
} else { // if element l1 bigger than l2
a[k] = l2[j]; // copy element l2 into original array
j++; // increment l2
}
k++; // increment original array
}
// copy remaining elements (if any)
while (i < n1) {
a[k] = l1[i];
i++;
k++;
}
while (j < n2) {
a[k] = l2[i];
j++;
k++;
}
printf("Your sorted array:\n");
for (int d = 0; d < n; d++) {
printf("%i ", a[d]); // print sorted array
}
printf("\n");
free(a); // freeing original array
}
You need to merge recursively. You wrote only the merge part and not the recursive sort function.
More info: https://www.geeksforgeeks.org/merge-sort/
#include <stdio.h>
#include <stdlib.h>
void merge(int arr[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
/* create temp arrays */
int L[n1], R[n2];
/* Copy data to temp arrays L[] and R[] */
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1 + j];
/* Merge the temp arrays back into arr[l..r]*/
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2) {
if (L[i] <= R[j]) {
arr[k] = L[i];
i++;
} else {
arr[k] = R[j];
j++;
}
k++;
}
/* Copy the remaining elements of L[], if there are any */
while (i < n1) {
arr[k] = L[i];
i++;
k++;
}
/* Copy the remaining elements of R[], if there are any */
while (j < n2) {
arr[k] = R[j];
j++;
k++;
}
}
void mergeSort(int arr[], int l, int r)
{
if (l < r) {
// Same as (l+r)/2, but avoids overflow for
// large l and h
int m = l + (r - l) / 2;
// Sort first and second halves
mergeSort(arr, l, m);
mergeSort(arr, m + 1, r);
merge(arr, l, m, r);
}
}
int main(void)
{
int *a, n;
printf("Enter n of elements in the array:");
scanf("%i", &n); //n of elements the in array
a = malloc(n * sizeof(int)); //dynamically allocating memory for original array
if (a == NULL)
return 1;
printf("Enter elements:\n");
for (int i = 0; i < n; i++) {
scanf("%i", &a[i]); //prompt user for input elements
}
mergeSort(a, 0, n - 1);
printf("Your sorted array:\n");
for (int d = 0; d < n; d++) {
printf("%i ", a[d]); //print sorted array
}
printf("\n");
free(a); //freeing original array
return 0;
}
I got an assignment - creating an array and finding the index of maximum element in the array.
I need to do it with Log(N) run-time so I made a binary tree function, which right know returns the value of maximum element.
I am trying to change to so it can return the index of the maximum element with no luck so far.
appreciate any kind of help.
the code is :
void max_value(int *a, int i, int n)
{
int j, temp;
temp = a[i];
j = 2 * i;
while (j <= n)
{
if (j < n && a[j + 1] > a[j])
j = j + 1;
if (temp > a[j])
break;
else if (temp <= a[j])
{
a[j / 2] = a[j];
j = 2 * j;
}
}
a[j / 2] = temp;
return;
}
int Array_Search(int *a, int n) {
int i;
for (i = n / 2; i >= 1; i--)
{
max_value(a, i, n);
}
return a[1];
}
How to reverse an array upto specified position in c#
static int[] ReverseArray(int[] arr, int i) {
int[] arrnew = new int[8];
int k = i;
for (int j = 0; j < k / 2; j++)
{
int temp = arr[j];
arr[j] = arr[k - j - 1];
arr[k - j - 1] = temp;
}
return arr;
}
so the question is about printing all the paths from top left to bottom right of a matrix. the movement allowed are down, right and diagonal. this has to be applied with obstacles, i.e if an obstacle is present then that path should not be printed.
So I wrote this code and if run the output is
1 4 7 8 9
1 4 5 8 9
1 4 5 8 9
1 4 5 9
1 4 8 9
1 5 8 9
1 5 8 9
1 5 9
line 3 and 7 the last second value needs to be 6. but instead, it's 8.
Any ideas?
TIA
#include<stdio.h>
#include<stdlib.h>
void paths(int *mat, int i, int j, int n, int *path, int val)
{
int k,l;
if (i == n - 1)
{
for(k = j; k < n; k++)
{path[val + k - j] = *((mat + i*n) + k);}
for(l = 0; l < val + n - j; l++)
{if(path[l] == 0){return;}}
for(l = 0; l < val + n - j; l++)
{
printf("%d ", path[l]);
}printf("\n");
return;
}
if (j == n - 1)
{
for(k = j; k < n; k++)
{path[val + k - i] = *((mat + k*n) + j);}
for(l = 0; l < val + n - j; l++)
{if(path[l] == 0){return;}}
for(l = 0; l < val + n - i; l++)
{
printf("%d ", path[l]);
}printf("\n");
return;
}
path[val] = *((mat + i*n) + j);
paths(mat, i+1, j, n, path, val+1);
paths(mat, i, j+1, n, path, val+1);
paths(mat, i+1, j+1, n, path, val+1);
}
void printAll(int *mat, int n)
{
int *path = malloc((2*n) * sizeof(int));
paths(mat, 0, 0, n, path, 0);
}
int main()
{
int n,i,j;
printf("Enter the size of the grid\n");
scanf("%d", &n);
int mat[n][n];
int count = 1;
for(i = 0; i < n; i++)
{
for(j = 0; j < n; j++)
{
mat[i][j] = count; count = count + 1;
}
}
printf("Enter the grid points that are offsets\n");
int obs[n*n][2];i=0;
while(1 == 1)
{
scanf("%d%d", &obs[i][0], &obs[i][1]);
mat[obs[i][0]][obs[i][1]] = 0;
if(obs[i][0] == -1 || obs[i][1] == -1){break;}
i = i + 1;
}
printf("The paths for the robot are\n");
printAll(*mat, n);
}
To get the correct output, change the for loop of the paths() function to:
for(k = i; k < n; k++)
{path[val + k - j] = *((mat + i*n) + k);}