Is this Bubble Sort or Quick Sort? - c

#include <stdio.h>
#include <conio.h>
#include <time.h>
#include <stdlib.h>
#define MAX 10
int main() {
int data[10], no, i, j, n, c;
printf("\n Enter no of elements :");
scanf("%d", &no);
printf("\nEnter the data");
for (i = 0; i < no; i++) {
scanf("%d", &data[i]);
}
n = MAX;
do {
for (i = 0; i < n - 1; i++) {
if (data[i] > data[i + 1]) {
data[i] = data[i] + data[i + 1];
data[i + 1] = data[i] - data[i + 1];
data[i] = data[i] - data[i + 1];
}
}
n = n - 1;
for (i = MAX - 1, c = 0; i >= c; i--) {
if (data[i] < data[i - 1]) {
data[i] = data[i] + data[i - 1];
data[i - 1] = data[i] - data[i - 1];
data[i] = data[i] - data[i - 1];
}
}
c = c + 1;
} while (n != 0 && c != 0);
printf("The sorted array is:");
for (i = 0; i < no; i++) {
printf("%d\t", data[i]);
}
}
I was confident it was bubble sort at first glance, until I saw the second looping – which confused me. Why would it sort from behind as well?
Could anyone tell me if it's a Bubble Sort or another type of sort?

Related

What is my C code not printing # in staircase pattern, this is from hackerrank, I did not pass all test cases, but i can't point out why?

Write a program that prints a staircase of size n.
I did not pass through all the test cases and don't understand where I made mistake.
This is my code:
void staircase(int n) {
char a[n][n];
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
if((i + j) > ((n / 2) + 1)) {
a[i][j] = '#';
printf("%c", a[i][j]);
} else {
printf(" ");
}
}
printf("\n");
}
}
Given Input
6
Expected Output
#
##
###
####
#####
######
Explanation:
The staircase is right-aligned, composed of # symbols and spaces, and has a height and width of n=6.
The problem is in the condition
if((i + j) > ((n / 2) + 1))
It should be
if(j >= n - i - 1) // or if(i + j >= n - 1)
To make this easier, I would create a helper function. Also, there's no need for the VLA a[n][n] that you don't even use for anything.
void repeat_char(int x, char ch) {
for(int i=0; i < x; ++i) putchar(ch);
}
void staircase(int n) {
for(int i = 1; i <= n; ++i) {
repeat_char(n - i, ' '); // or printf("%*s", n - i, "");
repeat_char(i, '#');
putchar('\n');
}
}
You do not need your a variable to do what you need. Here is a sample achieving what you want:
void staircase(unsigned n)
{
for (unsigned i = 0; i < n; ++i) {
for (unsigned j = 0; j < (n - i - 1); ++j)
printf(" ");
for (unsigned j = 0; j < (i + 1); ++j)
printf("#");
printf("\n");
}
}
The first loop is meant to cover every lines, then within it you make a loop which handles the spaces before the actual # symbols, and finally you make the loop handling the displaying of the symbols.
There is a much easier way of going about this than what you are trying to do:
#include <malloc.h>
#include <stdio.h>
#include <stdlib.h>
int main(void) {
const int n = 6;
char* str = malloc(sizeof(*str)*(n + 1));
if (str == NULL) {
printf("Somthing wrong with memory!\n");
return 1;
}
memset(str, ' ', n);
str[n] = '\0';
for(int i = n - 1; i > -1; i--) {
str[i] = '#';
puts(str); //or maybe printf who cares
}
free(str);
return 0;
}

Changing 6 different random numbers with SRAND in a board made with Dynamically Allocated Arrays

So, I have a code that creates a 7x7 board with Dynamically Allocated Arrays and inside of a board is full with "?" and what I want to do is creating a new function and inside a function, I used rand command to get random numbers like this,
int random() {
return ((rand() % 7) + 1);
}
Therefore, I had a problem changing 6 random numbers in a board and my Code is below,
This one below is the one I tried to get random numbers for an Array,
printf("Enter number: ");
scanf("%d", &b);
char *rando = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < b; i++) {
rand1 = random();
rand2 = random();
*(rando + rand1 + rand2) = '*';
}
And this one is where I printed the "?" signs and also where I tried to change 6 different signs and it only prints out "else" part ignoring the "if" for some reason
for (j = 0; j < 7; j++) {
if (*(board + i + j) == *(rando + i + j))
printf("| %c ", *(rando + i + j));
else
printf("| %c ", *(board + i + j));
}
And my whole code is this, it's kinda long but most of them are for a nice looking board
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int random() {
return ((rand() % 7) + 1);
}
int main() {
int i, j, k, rand1, rand2, b;
srand(time(NULL));
printf("Enter number: ");
scanf("%d", &b);
char *rando = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < b; i++) {
rand1 = random();
rand2 = random();
*(rando + rand1 + rand2) = '*';
}
char *board = (char *)malloc(7 * 7 * sizeof(char));
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
*(board + i + j) = '?';
}
}
for (i = 1; i <= 7; i++) {
printf("%4d", i);
}
printf("\n ");
for (i = 0; i < 7; i++) {
printf("+---");
}
printf("+\n");
for (i = 0; i < 7; i++) {
printf("%d ",i);
for (j = 0; j < 7; j++) {
if (*(board + i + j) == *(rando + i + j))
printf("| %c ", *(rando + i + j));
else
printf("| %c ", *(board + i + j));
}
printf("|\n");
for (k = 0; k <= 7; k++)
if (k == 0)
printf(" ");
else
printf("+---");
printf("+\n");
}
}
I pointed out important parts that I'm stuck with but still not sure if there is a problem in other parts of my code so I showed it here, just in case.
There are multiple problems in your code:
you allocate the 7x7 matrix as a single array of 49 characters. Yet you do not index into this array with the correct formula. The element at position (i,j) is accessed as *(board + 7 * i + j), not *(board + i + j).
It would be simpler to declare rando and board to point to a 2D matrix and use the [] syntax:
char (*board)[7] = malloc(7 * sizeof(*board));
and use board[i][j].
Furthermore, the rando array is uninitialized, so the program has undefined behavior when reading the contents of the elements that have not been set to '*' in the first loop. You must initialize this array with '?'. You can do this with memset().
the function random() returns an integer in the range 1 to 7 inclusive. You should instead compute pseudo-random coordinates in the range 0 to 6. Remove the +1;
the test in the board printing loop is useless: if the board element at position i,j is the same as in the rando matrix you print the rando element otherwise t board element. This always prints the board element.
Here is a modified version:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
int random(void) {
return rand() % 7;
}
void init_board(char board[7][7]) {
// board can be initialized with 2 nested loops or
// a single call to
//memset(board, '?', 7 * 7);
for (int i = 0; i < 7; i++) {
for (int j = 0; j < 7; j++) {
board[i][j] = '?';
}
}
}
void print_board(char board[7][7]) {
for (int i = 0; i < 7; i++) {
printf("%4d", i + 1);
}
printf("\n ");
for (int i = 0; i < 7; i++) {
printf("+---");
}
printf("+\n");
for (int i = 0; i < 7; i++) {
printf("%d ", i + 1);
for (int j = 0; j < 7; j++) {
printf("| %c ", board[i][j]);
}
printf("|\n");
printf(" ");
for (int j = 0; j < 7; j++) {
printf("+---");
}
printf("+\n");
}
}
int main() {
int b;
srand(time(NULL));
printf("Enter number: ");
scanf("%d", &b);
char (*rando)[7] = malloc(7 * sizeof(*rando));
if (!rando)
return 1;
init_board(rando);
for (int i = 0; i < b; i++) {
int rand1 = random();
int rand2 = random();
rando[rand1][rand2] = '*';
}
char (*board)[7] = malloc(7 * sizeof(*board));
if (!board)
return 1;
init_board(board);
/* print the mines */
print_board(rando);
/* print the board */
print_board(board);
free(rando);
free(board);
return 0;
}

unwanted element popping up in int list

I have written a C-program to generate random numbers and then sort them with the bubblesort-algorithm.
However, printing out the numbers (by an array, see the code) will show that the first element is 63, no matter what the randomly generated numbers were.
What causes this? And is there a more elegant way to bypass this than just skipping the first element of the list?
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("\n%d", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
for (int i = 0; i < 10; i++) {
printf("\n%d", list[i]);
}
In the inner loop of these loops
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i); j++) {
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
there is an access to the non-existent element of the array with the index 10
list[j] = list[j + 1];
^^^^^^
when j is equal to 9.
It si better to write the loop like
for (int j = 1; j < (10 - i); j++) {
if (list[j - 1] > list[j]) {
cache_num = list[j];
list[j] = list[j - 1];
list[j - 1] = cache_num;
}
You are going one past the array when the variable j reaches the value of 9. Use (10 - i - 1) to resolve the issue:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(void) {
int list[10];
int cache_num;
srand((unsigned) (time(NULL))); //Gives the rand() function a new seed from the current time
for (int i = 0; i < 10; i++) {
list[i] = rand();
printf("%d\n", list[i]);
}
for (int i = 0; i < 10; i++) {
for (int j = 0; j < (10 - i - 1); j++) { // note here ...
if (list[j] > list[j + 1]) {
cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
}
}
}
putchar('\n');
for (int i = 0; i < 10; i++) {
printf("%d\n", list[i]);
}
return 0;
}
Here in the following line you are going out of bounds because of which your are getting garbage value and thus altering your final result. Ex: when i=0 and j=9, this loops terminating condition will be is 9 < 10-0 which is true and it will execute. But for list [ j + 1 ] it will go out of bounds because there is no list [ 10 ].
for (int j = 0; j < (10 - i); j++){ ... }
It should have condition with -1 , (10-i-1)
for (int j = 0; j < (10 - i - 1); j++) { ... }
Instead of your implementation of the bubble sort to sort the data of 10 elements, you can use the below implementation.
The idea behind is that when you analyze (which you should) how the bubble-sort algorithm basically sorts the data, you will see a pattern i.e. in each pass of the inner-loop, the largest element (in-case of sorting the data in increasing order) will automatically go to its right location so, you don't need to consider that element again as it is already in its right position.
#include <stdio.h> // For basic I/O functions.
#include <stdlib.h> // For srand() & rand() functions.
#include <time.h> // For time(NULL) functions.
#define MAX_ARRAY_SIZE 10
int main(void) {
int list[10];
srand(time(NULL));
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
list[i] = rand();
}
// Implementation of Bubble-Sort
for(int i = (MAX_ARRAY_SIZE - 1); i >=0; --i) {
bool is_sorted = true;
for(int j = 0; j < i; ++j) {
if(list[j] > list[j + 1]) {
int cache_num = list[j];
list[j] = list[j + 1];
list[j + 1] = cache_num;
is_sorted = false;
}
}
if(is_sorted) {
break;
}
}
for(int i = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", list[i]);
}
printf("\n");
return 0;
}
P.S: As you are sorting only 10 elements, using bubble-sort is not going to make any difference, but I suggest you use insertion-sort instead of bubble-sort because insertion-sort is faster for small-size arrays.
Refer: Comparison Between Bubble-Sort/Selection-Sort/Insertion-Sort.
For Some Fun: Watch this bubble sort algorithm dance. 😁

Sort main diagonal of array by Shaker sort

So that's my task. I don't know how to realize it in 2D.
All variables (i, j, L, R, etc. are integer)
while (L < R)
{
for(i, j = L; i < R; i++, j++)
{
if (a[i][j] > a[i + 1][j + 1])
{
temp = a[i][j];
a[i][j] = a[i + 1][j + 1];
a[i + 1][j + 1] = temp;
k = i;
}
}
R = k;
for(i, j = R - 1; i >= L; i--, j--)
{
if(a[i][j] > a[i + 1][j + 1])
{
temp = a[i][j];
a[i][j] = a[i + 1][j + 1];
a[i + 1][j + 1] = temp;
k = i;
}
}
L = k + 1;
}
I tried this code but I think that something is wrong with that.
Input:
1 10 5
4 0 8
8 18 3
Output: (That should be)
0 10 5
4 1 8
8 18 3
But current Output is
1 10 5
4 0 8
8 18 3
A function to swap values using call by reference.
void swap(int *a, int *b)
{
int temp;
temp = *a;
*a = *b;
*b = temp;
}
A function implementing shaker sort
void ShakerSort(int a[], int n)
{
int i, j, k;
for(i = 0; i < n;)
{
// First phase for ascending highest value to the highest unsorted index.
for(j = i+1; j < n; j++)
{
if(a[j] < a[j-1])
swap(&a[j], &a[j-1]);
}
// Decrementing highest index.
n--;
// Second phase for descending lowest value to the lowest unsorted index.
for(k = n-1; k > i; k--)
{
if(a[k] < a[k-1])
swap(&a[k], &a[k-1]);
}
// Incrementing lowest index.
i++;
}
}
The main function looks like this
int main()
{
int n, i;
cout<<"\nEnter the number of data element to be sorted: ";
cin>>n;
int arr[n];
for(i = 0; i < n; i++)
{
cout<<"Enter element "<<i+1<<": ";
cin>>arr[i];
}
ShakerSort(arr, n);
// Printing the sorted data.
cout<<"\nSorted Data ";
for (i = 0; i < n; i++)
cout<<"->"<<arr[i];
return 0;
}
The above code is written in c++ refer it and make the changes according to your requirment

Find all Palindromes in a String Using C

I am trying to use C to print all Palindromes in a string and return the total number.
My code is returning all sorts of substrings which are not palindromes and printing blanks.
I am off by at least one in my printf statement formatting, but also, in my array element comparisons, it is working the opposite as I intended.
Can anyone see where I am going wrong?
Here is my code:
#include<stdio.h>
#include<string.h>
char x[1000];
void getString(char *n)
{
printf("\nPlease enter your string: ");
scanf("%s", n);
}
int findPals(char *s)
{
int length = strlen(s);
int numPals = 0;
//find odd palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
continue;
else
{
numPals++;
printf("%.*s\n", (j - i),s + i);
}
}
}
//find even palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i + 1 < length && i - j >= 0; j++)
{
if(s[i + j + 1] != s[i - j])
continue;
else
{
numPals++;
printf("%.*s\n", (j - i),s + i);
}
}
}
return numPals;
}
int main()
{
char inStr[1000];
int totalPals;
getString(inStr);
totalPals = findPals(inStr);
printf("I found %d palindromes.\n", totalPals);
return 0;
}
There are only 2 small corrections required in your code (given below) other than that everything is fine:-
1.Continue statement in the array checking should be changed to break:
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
break; // continue statement has been changed to break;
else
{
numPals++;
printf(".*s\n",(2*j)+1,&s[i-j]); // The length of the string has been modified
}
}
}
The string length in printf is incorrect.
For odd section use:
printf(".*s\n",(2*j)+1,&s[i-j]);
And for even section use:
printf(".*s\n",(2*j)+2,&s[i-j]);
Thanks for the help. Here is my final program.
#include<stdio.h>
#include<string.h>
char x[1000];
void getString(char *n)
{
printf("\nPlease enter your string: ");
scanf("%s", n);
}
int findPals(char *s)
{
int length = strlen(s);
int numPals = 0;
//find odd palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i < length && i - j >= 0; j++)
{
if(s[i + j] != s[i - j])
break;
else
{
if ((j + j) > 1)
{
numPals++;
printf("%.*s\n", ((2 * j) + 1), &s[i - j]);
}
}
}
}
//find even palindromes
for(int i = 0; i < length; i++)
{
for(int j = 0; j + i + 1 < length && i - j >= 0; j++)
{
if(s[i + j + 1] != s[i - j])
break;
else
{
if ((j + j) > 1)
{
numPals++;
printf("%.*s\n", ((2 * j) + 2), &s[i - j]);
}
}
}
}
return numPals;
}
int main()
{
char inStr[1000];
int totalPals;
getString(inStr);
totalPals = findPals(inStr);
printf("I found %d palindromes.\n", totalPals);
return 0;
}

Resources