Counting Sort 3

You are required to print the data associated with each integer. This means you will go through the original array to get the data, and then use some "helper arrays" to determine where to place everything in a sorted array.

If you know the frequencies of each element, you know how many times to place it, but which index will you start placing it from? It will be helpful to create a helper array for the "starting values" of each element.

Example:

Input:

10
4 that
3 be
0 to
1 be
5 question
1 or
2 not
4 is
2 to
4 the

Output:

1 3 5 6 9 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10 10 10 10 10 10 10 10 10 10 10
10 10 10 10

Approach:

Java

public class CountingSort3 {
    public static void main(String[] args) {
        int n = 10;
        int[] arr = { 4301512424 };
        String[] str = { "that""be""to""be"
                    "question""or"
                    "not""is""to""the" };
        int f[] = new int[100];
        for (int i = 0; i < n; i++) {
            int x = arr[i];
            f[x]++;
        }
        for (int i = 1; i < 100; i++) {
            f[i] = f[i] + f[i - 1];
        }
        for (int i = 0; i < 100; i++)
            System.out.print(f[i] + " ");
    }
}


C++

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int n = 10;
    vector<intarr = {4301512424};
    vector<stringstr = {"that""be""to""be",
                          "question""or""not",
                          "is""to""the"};
    int f[100] = {0};
    for (int i = 0i < ni++)
    {
        int x = arr[i];
        f[x]++;
    }
    for (int i = 1i < 100i++)
    {
        f[i] = f[i] + f[i - 1];
    }
    for (int i = 0i < 100i++)
        cout << f[i<< " ";
    return 0;
}


No comments:

Post a Comment