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.
Related
My task is: If we look at any two neighbour values in an array, if the one on the right is two times greater than the one on the left, their average should be inserted between them and the new array consisting of old and new elements should be printed. I have a problem with moving the other elements after average.And using special functions or libraries is not allowed.I am beginner, and I hope you could help.
#include <stdio.h>
int main() {
int n, i, j;
double a[100], average;
printf("Enter the number of elements: ");
scanf("%d", &n);
for (i = 0; i < n; i++) {
scanf("%lf", &a[i]);
}
for (i = 0; i < n; i++) {
if ((a[i + 1] / a[i]) == 2) {
for (i = j = 0; i < n; ++i)
b[j++] = a[i];
if (a[i + 1] / a[i] == 2)
average = (a[i + 1] + a[i]) / 2;
b[j++] =average;
}
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
}
A simple way to solve your problem is adding double b[199];, and copying everything over:
for (i = j = 0; i < n; ++i) {
b[j++] = a[i];
if (...) b[j++] = ...; /* Append the average to b. */
}
for (i = 0; i < j; ++i) {
printf("%lf\n", b[i]);
}
If you really want to move the elements forward within a itself, then you can do it by adding an inner for loop (and an additional loop variable int k;) which copies the elements one-by-one:
for (k = n++; k > i; --k) {
a[k] = a[k - 1];
}
In order to insert an element in an array, you must copy the elements with higher index from the last one down.
Also avoid dividing by a[i] that can be zero, and properly handle 0,0 that match the criteria for inserting the average, and skip the inserted value to avoid inserting more zeros.
#include <stdio.h>
#include <stdlib.h>
int main() {
int n, i, j;
printf("Enter the number of elements: ");
if (scanf("%d", &n) != 1 || n <= 0)
return 1;
double *a = malloc(sizeof(*a) * (2 * n - 1)); // allocate the array to the maximum size
if (a == NULL)
return 0;
for (i = 0; i < n; i++) {
if (scanf("%lf", &a[i]) != 1)
return 1;
}
for (i = 1; i < n; i++) {
if (a[i] == a[i - 1] * 2) {
for (j = n; j > i; j--)
a[j] = a[j - 1];
a[i] = (a[i - 1] + a[i]) / 2;
n++; // increase number of elements
i++; // skip the new value
}
}
for (i = 0; i < n; ++i) {
printf("%f\n", a[i]);
}
free(a);
return 0;
}
To insert an element in a specific position you would need to move the rest of the array. However doing it many times is expensive and you may prefer to use an array to store the position at which you want to insert the elements and then insert them all at once.
Alternatively you can create a new array where to copy the original plus the new values.
However there's an easier and faster way, that is adding the new values straight away, while you fill the original array. Here's a program that does that.
#include <stdio.h>
#define SIZE 100
int main() {
int i, n, avg = 0;
double a[SIZE];
while( puts("Enter the number of elements:") && (scanf("%d", &n) != 1 || n < 1 || n > SIZE) );
scanf("%lf", &a[0]);
for(i = 1; i < n+avg && i < SIZE-1 && scanf("%lf", &a[i]) == 1; i++) {
if( a[i] == a[i-1] * 2 ) {
a[i+1] = a[i];
a[i] = (a[i] + a[i-1]) / 2;
++avg;
++i;
}
}
for(i = 0; i < n+avg; i++) {
printf("%lf\n", a[i]);
}
return 0;
}
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.
this programme i wrote as an alternative way for bubble logic.it is working fine. but is it truly bubble logic programme or not
#include <conio.h>
#include <stdio.h>
int main()
{
int data[5], i, steps, temp, j, k;
int n = 5;
for (i = 0; i < n; ++i) {
printf("%d. Enter element: ", i + 1);
scanf("%d", &data[i]);
}
for (k = 0; k < n; k++) {
for (j = 0; j < n; j++) {
for (steps = 0 + j; steps <= j; steps++) {
printf("%d\n\n", steps);
if (data[steps] > data[steps + 1]) {
temp = data[steps];
data[steps] = data[steps + 1];
data[steps + 1] = temp;
}
}
}
}
printf("In ascending order: ");
for (i = 0; i < n; ++i) printf("%d ", data[i]);
getch();
}
any ideas?
Although bubble sort is a very inefficient sorting method, the "best" algorithm I found is (in pseudo code):
sort (A, n) // bubble sort array A[0..n-1]
k= n-1; // k holds position of last interchange. All higher elements are sorted.
while (k > 0)
{
l= 0;
for (j=0; j < k; j++)
{
if (A[j] > A[j+1])
{
tmp = A[j];
A[j] = A[j+1];
A[j+1]= tmp;
l= j;
}
}
k= l;
}
I wrote a program for bubble sort which is showing a run time error saying "NULL Pointer Assignment". The code is given below:
#include <stdio.h>
void main()
{
int a[6], j = 0, count = 0, i, temp;
printf("Enter the number");
for(i = 0; i< 4; i++)
{
scanf("%d", &a[i]);
}
while(count < 4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[++j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
count++;
}
printf("The sorted array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
But When I tried the below code then it runs successfully.
#include <stdio.h>
void main()
{
int a[6], count=0, i, temp;
printf("Enter the number");
for(i = 0; i < 4; i++)
{
scanf("%d", &a[i]);
}
while(count<4)
{
for(i = 0; i < 4; i++)
{
if(a[i] < a[i + 1])
{
temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
}
}
count++;
}
printf("The sort array is");
for(i = 0; i < 4; i++)
{
printf("\n%d\n", a[i]);
}
getchar();
}
So I need the reason that why my code is showing error, and why the 2nd code is working. I am a new learner in C so please explain to me the reason briefly and simply.
The reason you are getting a NULL pointer exception is in the first program, by the completion of the first iteration of the while loop the value of j has become 4. In the second iteration of the while loop the j value is not reset and continues from 4. Trying to access a[j] when j is equal to 6 will result in a the said error.
for (i = 0; i < n - 1; i++) {
for (j = 0; j <= i; j++) {
if(a[j] > a[j + 1]) {
// swap
}
}
}
Something like this will do the job.
The reason is that you don't reset the variable ´j´ at the beginning of the outer while loop and j is increased in the inner for loop. So you are increasing j in each of the 4 outer while loop transitions for 4 times in the inner for loop. So j has already reached the value 4 after the first while loop round. In the second while loop round it will be incremented to 5, 6, 7, 8 etc. So just reset the variable j to 0 at the beginning of the while loop:
while(count<4)
{
j = 0;
for(...
By the way it's still not a good implementation because you are comparing the last value with an undefined value: if(a[3] < a[4]).
Whereas a[3] contains the last entered value the variable a[4] contains an undefined value. Therefore you should change the for loop to for(i=0;i<3;i++).
I'm currently trying to learn C, and the exercise I found online has me creating a function that returns the index of the smallest value in an array. This is my function:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = 0;
for (int index = i; index < j; index++){
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
i and j are the lower and upper bound numbers the function should look in. For example, if i is 4 and j is 8, that means the function will return the index of the smallest value between indices 4 and 8.
Here is my main function:
#include <stdio.h>
int main(){
int numbers[10];
int user_input = 0;
for (int i = 0; i < 10; i++){
printf("Please enter a number: ");
scanf_s("%d", &user_input);
numbers[i] = user_input;
}
for (int i = 0; i < 10; i++){
int index_of_min_value = return_index_of_minimum(numbers, i, 10);
int old_num = numbers[index_of_min_value];
int new_num = numbers[i];
numbers[index_of_min_value] = new_num;
new_array[i] = old_num;
}
for (int i = 0; i < 10; i++){
printf("%d\n", new_array[i]);
}
}
The user would first enter a bunch of numbers and that would populate the array with the user's values. The idea is to use return_index_of_minimum to return the index of the smallest item in an array, and then set that equal to numbers[0] with a for loop, and then numbers[1], and then so on. old_num is the lowest number in the array, at its previous index. Here, I'm trying to swap that minimum value with whatever is at numbers[i] However, when I'm done sorting through the entire array, and am printing it out, I see that 10 (when the user enters 1-10 randomly for values) is at index 0, and then the rest of the numbers are in order. Does anybody see what is wrong here?
Here is a fix:
int return_index_of_minimum(int A[10], int i, int j){
int minimum_value = A[i];
int index_to_return = i;
...
}
Unfortunately this code doesn't have protection of invalid arguments, but otherwise this is an answer you've been looking for.
The reason is in call index_of_minimum(a, 9, 10): the loop performs only one iteration for index = 9, and because the minimum value is already initialized to value a[9], the index_to_return is not updated due to condition check.
This is a different approach that doesn't have same issue:
int return_index_of_minimum(int A[10], int i, int j){
/* assuming i < j */
int minimum_value = A[i];
int index_to_return = i; /* First element is a candidate */
for (int index = i + 1; index < j; index++){
/* Iterate from second element */
if (A[index] < minimum_value){
minimum_value = A[index];
index_to_return = index;
}
}
return index_to_return;
}
I believe there is an error in your return_index_of_minimum function.
int index_to_return = 0;
The problem lies I think here as the value of index_to_return will stay 0 if you call return_index_of_minimum(numbers, 5, 10); and that numbers[5] if the actual minimum.
However why not use a simple bubble-sort like the one implemented here
/*
* C program to sort N numbers in ascending order using Bubble sort
* and print both the given and the sorted array
*/
#include <stdio.h>
#define MAXSIZE 10
int main(void)
{
int array[MAXSIZE];
int i, j, num, temp;
printf("Enter the value of num \n");
scanf("%d", &num);
printf("Enter the elements one by one \n");
for (i = 0; i < num; i++)
{
scanf("%d", &array[i]);
}
printf("Input array is \n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
/* Bubble sorting begins */
for (i = 0; i < num; i++)
{
for (j = 0; j < (num - i - 1); j++)
{
if (array[j] > array[j + 1])
{
temp = array[j];
array[j] = array[j + 1];
array[j + 1] = temp;
}
}
}
printf("Sorted array is...\n");
for (i = 0; i < num; i++)
{
printf("%d\n", array[i]);
}
}