Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bubble sorting and getchar in c

I am working with microsoft visual studio 2012 and trying to make a bubble sort. Here is my code:

#include "stdafx.h"
#include "String.h"
#include <iostream>
#include <string.h>
using namespace std;

int main()
{
    int array[100], n, c, d, swap;
    printf("enter numbers of elements\n");
    scanf_s("%d",&n);
    printf("enter %d integers\n", n);
    for (c = 0; c < n; c++){
        scanf_s("%d", array);
    }
    for (c = 0; c < (n - 1); c++)
    {
        for (d = 0; d < n - c - 1; d++)
        {
            if (array[d]>array[d + 1]){
                swap = array[d];
                array[d] = array[d + 1];
                array[d + 1] = swap;
            }
        }
    }
    printf("sorted list in ascending order:\n");
    for (c = 0; c < n; c++){
        printf("%d\n", &array[c]);
    }
    getchar();
    return 0;
}

First of all I can't make console stay for a key entry. getchar() seems like not working but i don't have any error. Plus when I see console for a second, I can say that numbers are listed like "-310892". I don't know why.

like image 698
Koray Durudogan Avatar asked Oct 31 '22 03:10

Koray Durudogan


1 Answers

#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

int main(void)
{
    int array[100],n,c,d,flag,swap;
    printf("Enter the no. of elements\n");
    scanf("%d",&n);
    for(c=0;c<n;c++)
    {
        scanf("%d",&array[c]);  // here you have to add & for assigning a address to variable in memory 
    }


for(c=0;c<(n-1);c++)
{
    flag=0;
    for(d=0;d<n-c-1;d++)
    {
        if(array[d]>array[d+1])
        {
            swap=array[d];
            array[d]=array[d+1];
            array[d+1]=swap;
            flag=1;
        }

    }
    if(flag==0)
    break;
}
printf("sorted elements in ascending order:\n");
for(c=0;c<n;c++)
{
    printf("%d\t",array[c]);// you want to print the element not its address so no need of &
}
getch();    
return 0;}
  1. Please note i'm adding additional variable "flag" which helps to increase the efficiency of your program because the loop will break when your elements are done sorting but in your program the loop might be doing some extra iteration.
like image 187
Prince Vijay Pratap Avatar answered Nov 15 '22 05:11

Prince Vijay Pratap