A program sort array by remainder 3 - c

I was requested to write an effecient function with running time n which sort array by the remainder of 3 the program puts the elements which the remainder from dividing in 3 is 0 afterwards the elements that the remainder is 1 and afterwards 2
for example the array {7, 16, 3, 28, 12, 31, 14, 12}
will be sortes that way {12, 3, 12, 28, 16, 31, 7, 14}
so I tries to write an efficient function but it have not cover all cases and does not works for all arrays
int arr[] = { 7,16,3,28,12,31,14,12 };
int rem0 = 0, rem1 = 1, rem2 = 2;
for (int i = 0; i < 8; i++) {
if (arr[i] % 3 == 0)
rem0++;
if (arr[i] % 3 == 1)
rem1++;
if (arr[i] % 3 == 2)
rem2++;
}
int k = rem0, p = 0, m = 0 = 0;
for (int i = 0; i < 8; i++) {
while (rem0-k){
swap(&arr[i], &arr[rem0 - k]);
k--;
}
if (arr[i] % 3 == 1 && rem0+m<7) {
swap(&arr[i], &arr[rem0 + m]);
m++;
}
if (arr[i] % 3 == 1 && rem0 + rem1 + p<7) {
swap(&arr[i], &arr[rem0+rem1 + p]);
p++;
}
}
for (int l = 0;l <8;l++) {
printf("%d\n", arr[l]);
}
}
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
swap switch elements,
Can anyone tells me how can I fix that?
thanks:)

Since you want your function to run in O(n) time, you cannot sort the array completely. All you need to do is put all the elements in 3 buckets.
The following algorithm runs in 2 phases.
//First we count the number of elements in each bucket
int count[3] ={0, 0, 0};
for (int i = 0; i < NUM_ELEMENTS; i++) {
count[arr[i]%3]++;
}
Now that we have the number of elements, we can calculate the offsets of each bucket and create and output array
int output[NUM_ELEMENTS]; // In place bucketing can also be done using swaps
count[2] = count[0] + count[1];
count[1] = count[0];
count[0] = 0;
for (int i = 0; i < NUM_ELEMENTS; i++) {
output[count[arr[i]%3]] = arr[i];
count[arr[i]%3]++;
}
// Finally print the array
for (int i = 0; i < NUM_ELEMENTS; i++) {
printf("%d", output[i]);
}
Demo on Ideone

Here is the solution which you are looking for which uses the same array:
#include <stdio.h>
#define REMINDER 3
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<arr_size; i++) {
if (arr[i]%REMINDER==r) {
swap(&arr[idx++], &arr[i]);
}
}
}
for (int i=0; i<arr_size; i++) {
printf("%d ", arr[i]);
}
return 0;
}
Here is a another solution which is just simpler by using other place to store the result:
#include <stdio.h>
#define REMINDER 3
#define ARR_SIZE 10
int main()
{
int arr[ARR_SIZE] = {1,2,3,4,5,6,7,8,9,0};
int arr_sorted[ARR_SIZE];
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<ARR_SIZE; i++) {
if (arr[i]%REMINDER==r) {
arr_sorted[idx++]=arr[i];
}
}
}
for (int i=0; i<ARR_SIZE; i++) {
printf("%d ", arr_sorted[i]);
}
return 0;
}

Here's a 1-pass in-place Dutch national flag algorithm implementation (thanks to #Virgile who pointed out the algorithm)
void swap(int *a, int *b) {
int tmp = *a;
*a = *b;
*b = tmp;
}
// Dutch National Flag (see xlinux.nist.gov/dads/HTML/DutchNationalFlag.html)
void sort3dnf(int *a, size_t n) {
int *bot = a;
int *mid = a;
int *top = a + n - 1;
while (mid <= top) {
switch (*mid % 3) {
default: swap(bot++, mid++); break;
case 1: mid++; break;
case 2: swap(mid, top--); break;
}
}
}
See ideone.com/6QXXCN

hey thanks for the advice
sadly we had requested to write the code
without any added array
I will be very glad if you could help me to
solve the issue
thanks :)

hey thanks for the advice sadly we had requested to write the code without any added array I will be very glad if you could help me to solve the issue thanks :)
Here is the answer without adding any extra array:
#include <stdio.h>
#define REMINDER 3
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
int main()
{
int arr[] = {1,2,3,4,5,6,7,8,9,0};
int arr_size = sizeof(arr)/sizeof(arr[0]);
int idx=0;
for (int r=0; r<REMINDER; r++) {
for (int i=0; i<arr_size; i++) {
if (arr[i]%REMINDER==r) {
swap(&arr[idx++], &arr[i]);
}
}
}
for (int i=0; i<arr_size; i++) {
printf("%d ", arr[i]);
}
return 0;
}

Related

iterative permute function in C

I'm trying to write an iterative function that computes all the permutations of an array of numbers given in input.
Here is the code I've written so far.
void permute(int *a, int size){
int j=0, i, h=0, m;
bool flag=true;
int f = factorial(size);
int *arr, *res;
int counter=0;
arr = malloc(f*sizeof(int));
for(i=0; i<f; i++)
arr[i] = 0;
while (j < f) {
if(arr[j]<j)
{
if(j%2 == 0)
{
swap(a[0],a[j]);
} else {
swap(a[arr[j]], a[j]);
}
arr[j]++;
j=0;
} else{
arr[j] = 0;
j++;
}
printf("%d\n",a[j] );
}
}
The code doesn't compute well all the permutations and goes into a long loop. Can someone help me, please? Thanks to everyone.
Your code is close but includes some problems. For instance, the while loop
while (j < f) will assign j to a value out of bound of the array a.
Instead would you please try:
#include <stdio.h>
#include <stdlib.h>
int factorial(int x)
{
int i;
int y = 1;
for (i = 1; i <= x; i++) {
y *= i;
}
return y;
}
void swap(int *x, int *y)
{
int temp;
temp = *x;
*x = *y;
*y = temp;
}
void permute(int *a, int size)
{
int i, j = 0;
int f = factorial(size);
int *arr;
arr = calloc(f, sizeof(int)); // the members are initialized to 0
// print the original array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
while (j < size) {
if (arr[j] < j) {
if (j % 2 == 0) {
swap(a + 0, a + j);
} else {
swap(a + arr[j], a + j);
}
// print the rearranged array
for (i = 0; i < size; i++) {
printf("%d%s", a[i], i == size - 1 ? "\n" : " ");
}
arr[j]++;
j = 0;
} else {
arr[j] = 0;
j++;
}
}
free(arr);
}
int main()
{
int a[] = {1, 2, 3}; // example
permute(a, sizeof a / sizeof a[0]); // the 2nd argument is the array length
return 0;
}
Output of the example:
1 2 3
2 1 3
3 1 2
1 3 2
2 3 1
3 2 1

Local variable loses its value: selection sort algorithm

I previously tested the same variable called "swaps" for bubble sort algorithm and it worked perfectly. Now, with selection sorting, variable loses its value even after incrementing it.
Any help will be very much appreciated.
int list[] = {10, 5, 6, 3, 4, 11, 9, 7, 2};
int min = list[0], pos = 0, temp_max = 0;
// Loop until no swap is needed
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
int swaps = 0,
// Iterate through array to find min value
for (int i = j, y = sizeof(list) / sizeof(int); i < y; i++)
{
if (list[i] < min)
{
min = list[i];
pos = i;
}
}
// Insert min value in left most position and add 1 to swaps, meaning array is not yet sorted
if (pos > j)
{
temp_max = list[j];
list[j] = min;
list[pos] = temp_max;
swaps++;
}
// The error might occur here: "swaps" keeping value 0 after previous if statement ends
printf ("swaps = %d\n", swaps);
// If no swaps ocurred, array is sorted
if (swaps == 0)
{
// Print sorted array and return
}
}
Move the declaration int swaps = 0 outside the for loop.
In other words, change this:
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
int swaps = 0;
...
}
To this:
int swaps = 0;
for (int j = 0, n = sizeof(list) / sizeof(int); j < n; j++)
{
...
}
I want to thank you all very much. I have solved the problem with your help. Turns out the error had to do with the variable scope (where it was declared). Follow below the working code.
int main (void)
{
//Declare list to be sorted and other variables
int list[] = {9, 5, 7, 8, 4, 3, 2, 1, 6};
int minValPos = 0, maxTempVal = list[0];
for (int j = 0, siz = sizeof (list) / sizeof (int); j < siz; j++)
{
int swaps = 0, minVal = list[j];
// Look for min value after each j iteration
for (int i = j; i < siz; i++)
{
// Find minimum value (minVal) and store its position (minValPos)
if (list[i] < minVal)
{
minVal = list[i];
minValPos = i;
}
}
// Once with MinVal pinpointed, proceed to swap with jth item
if (minValPos > j)
{
maxTempVal = list[j];
list[j] = minVal;
list[minValPos] = maxTempVal;
swaps++;
}
// When array did not need any swaps, it means it is sorted
if (swaps == 0)
{
for (int r = 0; r < siz; r++)
{
printf ("Position [%d] = %d\n", r, list[r]);
}
}
}
}
That means your if statement is not becoming true in the meantime.
min should be set in each loop of j.
min=list[j] in for(j=...){min=list[j]; ... }
And also pos=j
Adding to the other answers, which will fix the problem specifically with your code, you can also approach the selection sort algorithm like this.
Steps to writing this algorithm for an array:
1. Write a helper function to find the index of the biggest element in the array:
size_t index_of_largest(int list[], size_t n) {
size_t i, biggest;
biggest = 0;
for (i = 0; i < n; i++) {
if (list[i] > list[biggest]) {
biggest = i;
}
}
return biggest;
}
2. Iterate over i=n to i=1, and find the biggest value between list[0] and list[i-1]. After this element is found, swap it into the last position. The function could look like this:
void sort_list(int list[], size_t n) {
size_t i, biggest;
for (i = n; i > 0; i--) {
biggest = index_of_largest(list, i);
int_swap(&list[biggest], &list[i-1]); /* swapping function */
}
}
3. Considering these ideas, you can write a simple version of the algorithm like this:
#include <stdio.h>
void sort_list(int list[], size_t n);
size_t index_of_largest(int list[], size_t n);
void print_array(int list[], size_t n);
void int_swap(int *x, int *y);
int main(void) {
int list[] = {10, 5, 6, 3, 4, 11, 9, 7, 2};
size_t n = sizeof list / sizeof *list;
printf("Before: ");
print_array(list, n);
sort_list(list, n);
printf("After: ");
print_array(list, n);
return 0;
}
void sort_list(int list[], size_t n) {
size_t i, biggest;
for (i = n; i > 0; i--) {
biggest = index_of_largest(list, i);
int_swap(&list[biggest], &list[i-1]);
}
}
size_t index_of_largest(int list[], size_t n) {
size_t i, biggest;
biggest = 0;
for (i = 0; i < n; i++) {
if (list[i] > list[biggest]) {
biggest = i;
}
}
return biggest;
}
void print_array(int list[], size_t n) {
size_t i;
for (i = 0; i < n; i++) {
printf("%d ", list[i]);
}
printf("\n");
}
void int_swap(int *x, int *y) {
int temp;
temp = *x;
*x = *y;
*y = temp;
}
Output:
Before: 10 5 6 3 4 11 9 7 2
After: 2 3 4 5 6 7 9 10 11
Compiled with:
gcc -Wall -Wextra -o progname progname.c

C_(visual)_Debug Error_ Run-Time Check Failure #2 -S

I want to reverse numbers of array,
but I can't understand why it didn't run.
Thanks for explaining what does Debug Error_ Run-Time Check Failure #2 -S mean..
Thanks,
#include <stdio.h>
int main()
{
int arr[] = { 1,2,3,4,5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d", arr[i]);
}
return 0;
}
Array index starts from 0 in C and your array has 5 elements so arr[4] is the last element but your code:
j = size - i;
arr[j];
when i=0 access to arr[5], this is your code error: Array index out of bound.
you should use j = size - i-1; to point to the last element of array, not j = size - i;
see this working sample (your sample code with some edit):
#include <stdio.h>
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int size, i, j;
int temp = 0;
size = sizeof(arr) / sizeof(arr[0]); //use this for changing size
printf("first_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i <= (size / 2); i++)
{
j = size - i - 1;
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
printf("Riv_array :");
for (i = 0; i < size; i++)
{
printf("%d ", arr[i]);
}
return 0;
}
another way to reverse array using pointers:
#include <stdio.h>
void reverse(int* p, int count){
int temp;
int* q = p + count - 1; // point to the end
count /= 2;
while (count--) {
temp = *p;
*p++ = *q;
*q-- = temp;
}
}
void print_array(int *p, int count){
while (count--) printf("%d ", *p++);
printf("\n");
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int count = ((&arr)[1] - arr);
print_array(arr, count);
reverse(arr, count);
print_array(arr, count);
return 0;
}
output:
1 2 3 4 5
5 4 3 2 1

Sort 2x3 Matrix without using qsort

My teacher has assigned something I can't seem to figure out how to do without using qsort. We're given a 2x3 array, and he wants us to sort each row from min to max. I am not allowed to use qsort for the purposes of learning; in my opinion, this is difficult.
Here is what I have so far; currently, the program crashes. I assume this is because when it gets to the third column, there isn't anything in a fourth column [j+1], so it returns an error.
#include "stdafx.h"
#include <stdio.h>
int main() {
int x[2][3] = { { 2, 3, -1 }, { 0, -3, 5 } }; //2x3 matrix; 2 rows, 3 columns
void sortMinMax(int b[][3], int numRow, int numColumn); //function prototype
sortMinMax(x, 2, 3);
return 0;
}
void sortMinMax(int a[][3], int numRow, int numColumn) {
for (int i = 0; i < numRow; i++) {
for (int j = 0; j < numColumn - 1; j++) {
if (a[i][j + 1] < a[i][j]) { //swap values if the next number is less than the current number
int temp = a[i][j];
a[i][j] = a[i][j + 1];
a[i][j + 1] = temp;
}
printf("%i\t", a[i][j]);
}
printf("\n");
}
return;
}
I appreciate any and all help!
I believe int i = 0; i <= numRow; i++ should be int i = 0; i <
numRow; i++
Why do you have if(i==0) & if(i==1) if you are doing the same stuff?
It looks like you tried to implement bubble-sort-like algorithm, but you do only one pass over the data
Here is an example of bubble sort algorithm
for(int x=0; x<n; x++)
{
for(int y=0; y<n-1; y++)
{
if(array[y]>array[y+1])
{
int temp = array[y+1];
array[y+1] = array[y];
array[y] = temp;
}
}
}
Slightly better alternative might be found # http://www.sorting-algorithms.com/bubble-sort
for i = 1:n,
swapped = false
for j = n:i+1,
if a[j] < a[j-1],
swap a[j,j-1]
swapped = true
→ invariant: a[1..i] in final position
break if not swapped
end
#include <stdio.h>
int main() {
int x[2][3] = { { 2, 3, -1 }, { 0, -3, 5 } };
void sortMinMax(int b[][3], int numRow, int numColumn);
sortMinMax(x, 2, 3);
for(int i = 0;i<2;++i){
for(int j = 0;j<3;++j)
printf("%i\t", x[i][j]);
printf("\n");
}
return 0;
}
void swap(int *a, int *b){
int tmp = *a;
*a = *b;
*b = tmp;
}
void sort3(int a[3]){
if(a[0] > a[1])
swap(&a[0], &a[1]);
if(a[0] > a[2])
swap(&a[0], &a[2]);
if(a[1] > a[2])
swap(&a[1], &a[2]);
}
void sortMinMax(int a[][3], int numRow, int numColumn) {
for (int i = 0; i < numRow; i++) {
sort3(a[i]);
}
}

bubble sort matrix with different col length

i need to do a bubble sort to matrix with different col lengths,
it need to be without the [] operand and in the language C.
i tried to do it like that :
for (i = 0; i < 5; i++)
{
first = (arr + i+d);// the first value in every line
for (j = 1; j <= (*first); j++)
{
for (d = 0; d <*(first)- j - 1; d++)
{
if (*(first+d+i) > *(first+d+1+i) )
{
swap =*(first+d);
*(first+d) = *(first+d+1);
*(first+d+1) = swap;
}
}
}
}
but it didn't work, someone can help me please ?
#include <stdio.h>
#include <stdlib.h>
typedef int Type;
#define PRN_Type "%d"
void print(Type **a, int size){
for(int i = 0;i<size;++i){
for(int j=1;j<=a[i][0];++j){
printf(PRN_Type " ", a[i][j]);
}
printf("\n");
}
}
void b_sort(Type **arr, int size){
int i, j, d;
Type swap, *first;
for (i = 0; i < size; ++i){
first = arr[i];//!!
for (j = 1; j <= *first; ++j){
for (d = 2; d <= *first -j+1; ++d){
if (*(first+d-1) > *(first+d) ){
swap =*(first+d-1);
*(first+d-1) = *(first+d);
*(first+d) = swap;
}
}
}
}
}
int main(void){
/*
int data[5][] = {
{3, 2,4,1},
{2, 99, 55},
{5, 9,5,1,7,5},
{1, 100},
{4, 5,5,5,5}
}
*/
int size = 5;
Type **data;
data = malloc(size * sizeof(Type*));
data[0]=(Type[]){3, 2,4,1};
data[1]=(Type[]){2, 99, 55};
data[2]=(Type[]){5, 9,5,1,7,5};
data[3]=(Type[]){1, 100};
data[4]=(Type[]){4, 5,5,5,5};
print(data, size);
b_sort(data, size);
printf("\n");
print(data, size);
return 0;
}

Resources