Looking for help describing this Algorithm for sorting an array. Is it a bubble or selection sort? Why do the elements switch?
#include <stdio.h> //including stdio.h for printf and other functions
#include <conio.h> //including conio.h for _getch() and other functions
int main() //default function for call
{
int a[10] = { 2,4,6,8 }; //Array declaration size-10
int n = 4; //Temporary number for array size
printf("\n\nArray Data : ");
flushall(); //Printing message
for (int i = 0; i < n; i++) //Loop for displaying the data of array
{
printf(" %d ", a[i]); //Printing data
}
for (int i = 0; i < n; i++) //Loop for ascending ordering
{
for (int j = 0; j < n; j++) //Loop for comparing other values
{
if (a[j] > a[i]) //Comparing other array elements
{
int tmp = a[i]; //Using temporary variable for storing last value
a[i] = a[j]; //replacing value
a[j] = tmp; //storing last value
}
}
}
}
This is a less efficient way of bubble sort.
You can find explanations here :
https://en.wikipedia.org/wiki/Bubble_sort#Step-by-step_example
A better code will be
for (int i = 0; i < n-1; i++)
for (int j = 0; j < n-i-1; j++)
if (arr[j] > arr[j+1])
{
// swap temp and arr[i]
int temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
It reduces number of comparisons and looping by optimizing the upper limit of loops.
You can see a video on this here.
Related
For example i have an array {1,2,2,2,3,3,3,3,4,4,4,4,4,}
I need to transform it into {4,4,4,4,4,,3,3,3,3,2,2,2,1}
So i have to sort it by the number of repetitions of an array element somehow.
I saw some solves of this problem on c++ but i have to write it on C.
I can`t use vector or smth. Just Sorting with buffer array or inside of exact array.
I tried something like this, but honestly now i etched into a dead end:
It is dont work properly as i ment.
I have an algoritm in my head:
Program count how times some element was repeated and write in into a second array
Program sort second array
Program sort first array by second array somehow
#include <stdio.h>
int main()
{
const int size = 10;
int A[size], B[size];
int counter1, counter2 = -1;
int temp = 0;
for (int i = 0; i < size; i++) {
printf("Enter %d element of array: ", i + 1);
scanf_s("%d", &A[i]);
}
for (int i = 0; i < size-1; i++) {
counter1 = 0;
counter2++;
for (int j = i; j < size; j++) {
if (A[j] == A[j - 1]) {
break;
}
if (A[j] == A[j+1]) {
counter1++;
B[counter2] = counter1;
temp = A[i];
}
}
}
for (int i = 0; i < size; i++) {
printf("El %d = %d\n",i+1,B[i]);
}
}
Not the best, but it does the job! I'm storing the final result in the Result[len][2]; variable! you can modify the code as you like
#include <stdio.h>
#include <string.h>
int main( )
{
int array[] = {1,2,2,2,3,3,3,3,4,4,4,4,4,11,10,6,6,6,6,6,6,6,6,6,6,6,6,};
int i,j,k=0,l,len,flag=0,temp0, temp1;
len = sizeof(array)/sizeof(array[0]);
int Result[len][2];
memset(Result,0,sizeof(Result));
for (i = 0 ;i < len ; i++ )
{
if (k != 0)
{
for (l= 0 ;l < k ; l++ )
if (array[i]== Result[l][0]) goto skip;
}
for(j= i ; j < len ; j++ )
{
if (array[i] == array[j])
{
Result[k][0] = array[j];
Result[k][1]++;flag = 1;
}
}
skip: if (flag == 1) {k++; flag = 0;}
}
for (i = 0; i < k; i++)
{
for(j= i+1 ; j < k ; j++ )
{
if(Result[i][1] < Result[j][1])
{
temp0 = Result[i][0];
temp1 = Result[i][1];
Result[i][0] = Result[j][0];
Result[i][1] = Result[j][1];
Result[j][0] = temp0 ;
Result[j][1] = temp1 ;
}
}
}
for (i = 0; i < k; i++) printf("[%d][%d]\n",Result[i][0],Result[i][1]);
return 0;
}
The output at my computer under the Linux environment is as follows:
[6][12]
[4][5]
[3][4]
[2][3]
[11][1]
[10][1]
[1][1]
how can I sort an array by the number of repetitions
Sort array A of size m by value .
Walk array and count number of different values: n
Allocate array B[] of size n of structs that has 2 members: value and occurrence.
Walk array A[] again and populate B[]
Sort B[] by .occurrence.
Walk B[] and re-populate A[].
O(m) memory, O(m *log m) time.
I want to put random numbers from 1 to 16 in a two-dimensional array without duplication.
I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.
Which part is wrong and why?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int A[4][4];
int i, j, k, l;
int num;
srand(time(NULL));
int count;
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
//Re:
num = rand() % 16 + 1;
A[i][j] = num;
for(k = 0; k <= i; k++)
{
count = 0;
for(l = 0; l <= j; l++)
{
if(A[k][l] == num)
{
if(k != i && l != j)
{
j--;
count = 1;
break;
// goto Re;
}
}
}
if(count == 1)
break;
}
}
}
for(i = 0; i < 4; i++)
{
for(j = 0; j < 4; j++)
{
printf("%3d", A[i][j]);
}
printf("\n");
}
}
I want to put random numbers from 1 to 16 in a two-dimensional array without duplication. I made a code that eliminates duplicates and puts new random numbers back into the array, but it keeps printing duplicate numbers.
Put the numbers 1,…,16 into an array tmp.
Perform a Fisher-Yates shuffle on tmp.
Iterate through tmp to copy its elements to A using the mapping A[i/4][i%4] = tmp[i].
If you’re not convinced, try a few values of i by hand to assure yourself this works.
I want to generate numbers from 1 to 10 in an array, then print them in descending order. The method I’ve used so far doesn’t work properly. Sometimes the number 10 is at the bottom, and all other numbers are correctly ordered.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a[7], j, i;
srand(time(NULL));
a[0] = rand() % 10;
int length = 7;
for(int i = 0; i < 7; i++) {
int duplikat = 0;
a[i] = rand() % 10+1;
for (int j=0; j<i; j++) {
// descending order: Just change (a[j] > a[j+1])
if(a[i] == a[j]) duplikat = 1;
if (a[j] < a[j+1]) {
int temp = a[j];
a[j] = a[j + 1];
a[j + 1] = temp;
}
if (duplikat) i--;
}
}
for(int i = 0; i< length; i++) {
printf("a[%d] = %d\n", i, a[i]);
}
printf("\n");
for(j=0;j<7;j++) printf("\n%d ", a[j]);
return 0;
}
Some observations:
The line if (duplikat) i--; should be outside the inner loop over j, so that you decrease i at most once when a dupicate is found.
Fiddling with the index of a for loop to implement some skipping logic is also very brittle. Instead, consider a while loop until your array a is full where you add items only if they are no duplicates.
If you want to "bubble down" the new number so that the part of the array is sorted, you must start from the right-hand side of the array. Otherwise, the only swap that may take place is of the new item with the last item in the array.
You could do something similar to insertion sort, where you keep the generated array sorted at all times:
Determine a new random number to add, the "pick".
Find the place i where the pick goes; if the number was already generated, pick again.
Otherwise, create an empty slot at the end of the array by incrementing the actual length, then move all elements right of the i one place to the right. There is now a gap at i, where you place your pick.
Repeat until your array has enough items.
In code:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void)
{
int a[7];
int length = 7; // desired length of array
int n = 0; // current length of array
srand(time(NULL));
while (n < length) {
int pick = rand() % 10 + 1;
int i = 0;
// skip greater elements
while (i < n && pick < a[i]) i++;
// shift smaller elements and add pick if it is unique
if (i == n || pick != a[i]) {
int j = n++;
while (i < j) {
a[j] = a[j - 1];
j--;
}
a[i] = pick;
}
}
// print array
for (int i = 0; i< length; i++) {
if (i) printf(", ");
printf("%d", a[i]);
}
printf("\n");
return 0;
}
I wrote to program in C to attempt to print array elements in descending order. I wrote a nested loop which would find the maximum element of the array and the value of the element would be set to later 0. This process would be repeated for all the elements. However, in the output, I am getting the first 2-3 values as desired but the remaining values are garbage. Any suggestions?
int main() {
int i, j, n, k;
scanf("%d\n", &n);
int a[100], b[100];
for (i = 0; i < n; i++) {
scanf("%d", &a[i]);
}
for (i = 0; i < n; i++) {
int max = a[i];
for (j = i; j < n; j++) {
if (a[j] > max) {
max = a[j];
b[i] = max;
}
}
for (k = 0; k < n; k++) {
printf("%d", a[k]);
if (a[k] == b[i]) {
a[k] = 0;
}
}
printf("\n");
}
for (i = 0; i < n; i++) {
printf("%d ", b[i]);
}
}
The main issue is that you only set b[i] = max; when you find a new max, but since you initialized max to be a[i] it could happen that it already holds the maximum value. So the if never executes, therefore b[i] is not written and there's garbage value in it. You should move this line from the if after that for loop.
Another issue is that you initialize j with i in this loop. You should initialize it to 0.
The changed part:
for (j = 0; j < n; j++) {
if (a[j] > max) {
max = a[j];
}
}
b[i] = max;
Write a C program to perform bubble sort on an array of n elements.
I write the following code but the condition is that stop the process if we find that the list is sorted in any intermediate point
pls tell how i solve this??
#include <stdio.h>
#include <conio.h>
void bubble_sort(int[], int);
void main() {
int arr[30], num, i;
printf("\nEnter no of elements :");
scanf("%d", &num);
printf("\nEnter array elements :");
for (i = 0; i < num; i++)
scanf("%d", &arr[i]);
bubble_sort(arr, num);
getch();
}
void bubble_sort(int iarr[], int num) {
int i, j, k, temp;
printf("\nUnsorted Data:");
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
for (i = 1; i < num; i++) {
for (j = 0; j < num - 1; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
printf("\nAfter pass %d : ", i);
for (k = 0; k < num; k++) {
printf("%5d", iarr[k]);
}
}
}
The trick is to count or test if there was any swap when you iterate through the list elements in the inner loop, if there was no need to swap any element, that certainly means that the list is sorted.
The idea behind the bubble sort is that on each iteration largest element in the list reaches at the end.
SO After first iteration largest element of the array reaches at the end. Similarly, at the second iteration second largest element in array reaches at the second last position and so on.
so you have to make some change in your j variable loop.
Make it like this:
for (i = 1; i < num; i++) {
for (j = 0; j < num - i; j++) {
if (iarr[j] > iarr[j + 1]) {
temp = iarr[j];
iarr[j] = iarr[j + 1];
iarr[j + 1] = temp;
}
}
By this J loop will iterate only to those elements which are not sorted.