Skip to main content

Featured

Merge Sort in C++

  Merge Sort in C++ Introduction Merge Sort is a popular sorting algorithm that follows the Divide and Conquer approach. It divides an array into smaller subarrays, recursively sorts those subarrays, and finally merges the sorted subarrays to produce a completely sorted array. In this tutorial, we will learn how to implement Merge Sort in C++ . The program divides the array into two halves using the mid index, recursively sorts both halves, and then combines them using the merge() function. Merge Sort has a time complexity of O(n log n) in the best, average, and worst cases. Table of Contents Algorithm C++ Program Input Sample Output Output Explanation Dry Run Flow of Execution Time Complexity Space Complexity Applications Key Points Interview Questions Frequently Asked Questions Keywords Conclusion Algorithm Start the program. Read the size of the array. Read the array elements from the user. Call the mer...

C Program to Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

Remove Duplicates and Sort Characters in Descending Order - C Program

๐Ÿš€ C Program to Remove Duplicates, Ignore Spaces, and Sort Characters in Descending Order

๐Ÿ“„ Source Code:


#include<stdio.h>
#include<string.h>

int present(char a[], char ch, int len)
{
    for (int i = 0; i < len; i++)
    {
        if (a[i] == ch)
        {
            return 1;
        }
    }
    return 0;
}

void des(char a[], int len)
{
    for (int i = 0; i < len - 1; i++)
    {
        for (int j = i + 1; j < len; j++)
        {
            if (a[i] < a[j])
            {
                char temp = a[i];
                a[i] = a[j];
                a[j] = temp;
            }
        }
    }
}

int main()
{
    char str[200], result[200];
    int j = 0;
    fgets(str, sizeof(str), stdin);
    int len = strlen(str);
    if (str[len - 1] == '\n')
    {
        str[len - 1] = '\0';
    }

    for (int i = 0; str[i] != '\0'; i++)
    {
        if (str[i] != ' ' && !present(result, str[i], j))
        {
            result[j++] = str[i];
        }
    }

    des(result, j);
    result[j] = '\0';

    printf("Resulting string: %s\n", result);
}
    

๐Ÿ“˜ Deep Explanation:

This C program performs three core operations on a string entered by the user:

  • ๐Ÿ”น 1. It removes duplicate characters from the string.
  • ๐Ÿ”น 2. It ignores spaces.
  • ๐Ÿ”น 3. It sorts the unique characters in descending order.
  • ๐Ÿ”ธ present() checks if a character is already in the result array.
  • ๐Ÿ”ธ des() uses a simple bubble sort in descending (Z to A) order.
  • ๐Ÿ”ธ fgets() is used instead of scanf() to read spaces.
  • ๐Ÿ”ธ Only unique characters are printed after sorting.

๐Ÿงช Sample Output:


Input:
Hello World

Output:
Resulting string: roledWH
    

Comments

Popular Posts

๐ŸŒ™