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:
104 that3 be0 to1 be5 question1 or2 not4 is2 to4 the
Output:
1 3 5 6 9 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10 10 10 10 10 10 10 10 10 10 1010 10 10 10
Approach:
Java
public class CountingSort3 {public static void main(String[] args) {int n = 10;int[] arr = { 4, 3, 0, 1, 5, 1, 2, 4, 2, 4 };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<int> arr = {4, 3, 0, 1, 5, 1, 2, 4, 2, 4};vector<string> str = {"that", "be", "to", "be","question", "or", "not","is", "to", "the"};int f[100] = {0};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++)cout << f[i] << " ";return 0;}
No comments:
Post a Comment