In bubble sort, when first iteration of the inner for loop takes place, value of i is 0, so the loop will run till j is less than n, but when j becomes equal to n-1, and we do a[j+1] for another time.
why doesn't this value go out of index of the array and the code executes properly?
for(i=0;i<n-1;i++) {
for(j=0;j<n-i;j++) { /* When i=0 & j<n why doesn't */
if(a[j] > a[j+1]) { /* a[j+1] go out of index when */
temp=a[j+1]; /* value of j is n-1 */
a[j+1]=a[j];
a[j]=temp;
}
}
}
Well this is a proper , Tested Bubble Sort function:
void bubble_sort(long a[], long n)
{
long i, j, t;
for (i = 0 ; c < ( n - 1 ); i++)
{
for (j = 0 ; j < n - i - 1; j++)
{
if (a[j] > a[j+1])
{
t = a[j];
a[j] = a[j+1];
a[j+1] = t;
}
}
}
}
I think the problem is with you second for's, second argument.
It should run till j is less than i, not n.
void bubble(double *t, int db) {
int i, j;
for (i = db-1; i > 0; --i)
for (j = 0; j < i; ++j)
if (t[j+1] < t[j]) {
double temp = t[j];
t[j] = t[j+1];
t[j+1] = temp;
}
}
Related
Im trying to sort a matrix by the sum of its row's digits, from highest to lowest. I dont know if i explained that correctly so here's some photos explaining it.
This is what my code outputs. Basically, it asks you for m and n, which are the dimensions of the matrix. In this example it's a 3x4, 3 rows and 4 columns. Then, the matrix should be sorted by rows, by the sum of row's digits. Which means, instead of what's being outputted in the picture above, the correct result should be this:
I have no idea how to sort this from highest to lowest, i have been trying for hours to no avail.
Here's my code:
#include <stdio.h>
#define N 30
void main(){
double a[N][N], s[N], p;
int i, j, m, n, max;
while(1){
printf("\nm, n? ");
scanf("%d%d", &m, &n);
if(m <= 0 || m > N || n <=0 || n > N)
break;
for(i = 0; i < m; i++){
printf("%2d. row? ", i+1);
for(j = 0; j < n; scanf("%lf", &a[i][j++]));
}
for(i = 0; i < m; i++)
for(s[i] = j = 0; j < n; s[i] += a[i][j++]);
for(j = 0; j < n - 1; j++){
for(max = i, j = i+1; j < n; j++)
if(s[j] > s[max])
max = i;
if(max != j){
p = s[j];
s[j] = s[max];
s[max] = p;
for(j = 0; j < m; j++){
p = a[j][i];
a[j][i] = a[j][max];
a[j][max] = p;
}
}
}
printf("New matrix: \n");
for(i = 0; i < m; i++){
for(j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for(j = 0; j < m; j++)
printf("-------------");
printf("\n");
for(j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
}
You can sort the rows of the matrix from highest to lowest, using a simple bubble sort algorithm.Your code modified below:
int main() {
double a[N][N], s[N], p;
int i, j, m, n, max;
while (1) {
printf("\nm, n? ");
scanf("%d%d", & m, & n);
if (m <= 0 || m > N || n <= 0 || n > N)
break;
for (i = 0; i < m; i++) {
printf("%2d. row? ", i + 1);
for (j = 0; j < n; scanf("%lf", & a[i][j++]));
}
for (i = 0; i < m; i++)
for (s[i] = j = 0; j < n; s[i] += a[i][j++]);
for (i = 0; i < m - 1; i++) { // modified here
for (j = i + 1; j < m; j++) { // modified here
if (s[j] > s[i]) { // modified here
p = s[i];
s[i] = s[j];
s[j] = p;
for (int k = 0; k < n; k++) {
p = a[i][k];
a[i][k] = a[j][k];
a[j][k] = p;
}
}
}
}
printf("New matrix: \n");
for (i = 0; i < m; i++) {
for (j = 0; j < n; printf("%8.2lf", a[i][j++]));
printf("\n");
}
for (j = 0; j < m; j++)
printf("-------------");
printf("\n");
for (j = 0; j < m; printf("%8.2f \n", s[j++]));
printf("\n");
}
return 0;
}
Here's how i modified your code to achieve that:
Initialize a loop variable i to 0.
In the outer loop, run the inner loop j from i+1 to m-1.
In the inner loop, compare the sum of the row i with the sum of row
j. If the sum of row j is greater than the sum of row i, swap the
rows using a temporary variable.
After the inner loop finishes, increment the value of i by 1. Repeat
the outer loop until i becomes equal to m-1.
Output:
You can just use qsort to let it handle the sorting and item swapping. Then you only need to write the code for comparing two rows with each other.
Given something like this:
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
You'd call qsort as:
qsort(matrix, 3, sizeof(int[4]), compare);
The only complexity is implementing the comparison callback function. There's two things to consider there:
We've told qsort that we have an array of 3 items, each of type int[4]. So the void pointers it passes along to us will actually be pointers to type int[4]. That is: int(*)[4].
qsort sorts in ascending order by default, where the item considered "less" ends up first. So we need to tweak that to get the largest item first.
Example:
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
sum1 < sum2 would have placed the smallest row first.
Full example:
#include <stdio.h>
#include <stdlib.h>
int compare (const void* obj1, const void* obj2)
{
const int (*ptr1)[4] = obj1;
const int (*ptr2)[4] = obj2;
size_t sum1=0;
size_t sum2=0;
for(size_t i=0; i<4; i++)
{
sum1 += (*ptr1)[i];
sum2 += (*ptr2)[i];
}
if(sum1 > sum2) // largest sum considered "less" for qsort
return -1;
else
return 1;
return 0;
}
void print_matrix(size_t col, size_t row, int matrix[col][row])
{
for(size_t i=0; i<col; i++)
{
for(size_t j=0; j<row; j++)
{
printf("%d,", matrix[i][j]);
}
puts("");
}
}
int main (void)
{
int matrix[3][4] =
{
{1,2,3,4},
{5,6,7,8},
{9,1,2,3},
};
print_matrix(3,4,matrix);
puts("");
qsort(matrix, 3, sizeof(int[4]), compare);
print_matrix(3,4,matrix);
}
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;
Hi I'm using gdb to debug my bubble sort code but I don't get why it keeps breaking at if(a[j] < a[j-1]
here is my bubble sort function
void sort(int a[], int n) {
int i, j, nswaps, tmp;
for(i = 0; i < n; i++) {
nswaps = 0;
for(j = 0; j > i; j++) {
if(a[j] < a[j-1]) {
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
nswaps++;
}
}
if(nswaps == 0) break;
}
}
Please do help me thanks!!
updated code: still has a segmentation fault
void sort(int a[], int n) {
int i, j, nswaps;
for (i = 0; i < n; i++) {
nswaps = 0;
for (j = 1; j > i; j++) {
if (a[j] < a[j-1]) {
int tmp;
tmp = a[j];
a[j] = a[j-1];
a[j-1] = tmp;
nswaps++;
}
}
if (nswaps == 0) break;
}
}
In the first iteration of the outer loop (when value of i is 0), the inner loop becomes an infinite loop, because value of j starts from 0 and keeps increasing. Eventually j becomes large enough for your program to access some unallocated memory, hence causing a segmentation fault.
Also, in the first iteration of the inner loop, value of j is 0, so a[j - 1] will try to access a memory location out of bound for your program.
j > i is false on the first iteration, so if(nswaps == 0) is true and the loops break, no sorting occurs.
Instead of iterating the outside loop n times, iterate n-1 times.
No need to count swaps, a simply boolean is sufficient.
After the first inner loop iteration, the lowest element of the array is found and in place at the end. The next inner loop only needs to iterate to next-last element, etc.
size_t is the Goldilocks type for array indexing, neither too narrow, nor too wide. Better than using int for indexing. Remember that is is an_unsigned type_.
No need to declare a variable until needed.
#include <stdbool.h>
#include <stdlib.h>
void bubble_sort(int a[], size_t n) {
while (n > 1) {
bool swapped = false;
for (size_t j = 1; j < n; j++) {
if (a[j-1] < a[j]) {
int tmp = a[j];
a[j] = a[j - 1];
a[j - 1] = tmp;
swapped = true;
}
}
if (!swapped) {
break;
}
n--;
}
}
Hello this is my method for a String Array insertion sort. It is returning bogus results to the console. Mainly just one array element over and over. Any help what needs to be changed is greatly appreciated.Thank you.
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i - 1 ;
while (j >= 0 && a[j].compareTo(Value)> 0) {
a[j+1] = a[j];
j=j-1;
}
a[i+1] = Value;
}
}
The code below works.
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i;
while (j > 0 && a[j-1].compareTo(Value)> 1) {
a[j] = a[j-1];
j--;
}
a[j] = Value;
The problem is a[j+1] = a[j];
Your original a[j+1] would be lost, you just simply replace it, without moving it / storing it, it is just simply replaced by a[j] and get lost...
I would modify your code like the following:
Find the position of current value to be inserted, swap it with the element at that position, then swap back that element into correct position
public static void insertionSort(String[] a, int count) {
int i, j;
String Value;
for (i = 1; i < count; i++) {
Value = a[i];
j = i - 1 ;
int p = i;
while (j >= 0 && a[j].compareTo(Value)> 0) {
p = j--;
}
// p now is correct position to be inserted
swap(a[p], a[i]);
// Now loop the original a[p] back to a[p+1]
for(int z = i; z > p; z--){
swap(a[z], a[z-1]);
}
}
}
check the code works fine
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
and to print the number i use function printNumbers(array)
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
I have one array of elements with 1 5 9 (e.g. a1 a2 a3)
and second array of elements with 2 4 8 (e.g. b1 b2 b3)
I want the output to be 1,2 5,4 9,8 (i.e. a1,b1 a2,b2 a3,b3)... Is it possible?
All the loops I tried sort the entire thing like 1,2,4,5,8,9?
Code block:
void merge(int a[], int m, int b[], int n, int sorted[]) {
int i, j, k;
j = k = 0;
for (i = 0; i < m + n;) {
if (j < m && k < n) {
if (a[j] < b[k]) {
sorted[i] = a[j];
j++;
}
else {
sorted[i] = b[k];
k++;
}
i++;
}
else if (j == m) {
for (; i < m + n;) {
sorted[i] = b[k];
k++;
i++;
}
}
else {
for (; i < m + n;) {
sorted[i] = a[j];
j++;
i++;
}
}
}
}
Your condition:
if (a[j] < b[k]) {
enforces sorting, but you said you didn't want sorting, so don't do it.
I'd prefer a simpler looping structure:
while (j < m && k < n)
{
sorted[i++] = a[j++];
sorted[i++] = b[k++];
}
while (j < m)
sorted[i++] = a[j++];
while (k < n)
sorted[i++] = b[k++];
This is more nearly idiomatic C.
The requirement in the question doesn't depend on the input arrays being sorted — it simply interleaves the elements of the two arrays in sequence until one or the other runs out of data, and then copies the rest (if any) of the other array to the output.
It is possible to simplify this code — it doesn't need both j and k:
int i = 0;
int j;
int min = (m < n) ? m : n;
for (j = 0; j < min; j++)
{
sorted[i++] = a[j];
sorted[i++] = b[j];
}
while (j < m)
sorted[i++] = a[j++];
while (j < n)
sorted[i++] = b[j++];
Only one of the while loops will execute the body of the loop, but the while conditions make a separate if test superfluous.
int k = m < n ? n : m;
int j = 0;
for (int i = 0; i < k; i++)
{
if (i < m && i < n)
{
sorted[j++] = a[i];
sorted[j++] = b[i];
}
else
{
while (i < m)
{
sorted[j++] = a[i++];
}
while (i < n)
{
sorted[j++] = b[i++];
}
}
}
Try this....
int i,j,k,m;
int arr[] = {1,5,9};
int arr1[] = {2,4,8};
int l1 = sizeof(arr)/sizeof(int);
int l2 = sizeof(arr1)/sizeof(int);
int arr3[l1+l2];
int l3 = sizeof(arr3)/sizeof(int);
j=0;
k=0;
if(l1>=l2){
for(i=0;i<l1;){
if(arr[i]<arr1[j]){
arr3[k]=arr[i];
i++;
k++;
}else{
arr3[k]=arr1[j];
k++;
j++;
}
if(j==l2){
arr3[k]=arr[i];
i++;
k++;
}
}
}
for(i=0;i<l3;i++){
printf("%d ",arr3[i]);
}
Output
1 2 4 5 8 9
If you want output like this 1,2 5,4 9,8
then change your ifcondition
if (j < m && k < n) {
sorted[i++] = a[j];
j++;
sorted[i++] = b[k];
k++;
}