The Full Counting Sort


Problem Statement :


Use the counting sort to order a list of strings associated with integers. If two strings are associated with the same integer, they must be printed in their original order, i.e. your sorting algorithm should be stable. There is one other twist: strings in the first half of the array are to be replaced with the character - (dash, ascii 45 decimal).

Insertion Sort and the simple version of Quicksort are stable, but the faster in-place version of Quicksort is not since it scrambles around elements while sorting.

Design your counting sort to be stable.


Function Description

Complete the countSort function in the editor below. It should construct and print the sorted strings.

countSort has the following parameter(s):

string arr[n][2]: each arr[i] is comprised of two strings, x and s
Returns
- Print the finished array with each element separated by a single space.

Note: The first element of each , , must be cast as an integer to perform the sort.

Input Format

The first line contains , the number of integer/string pairs in the array .
Each of the next  contains  and , the integers (as strings) with their associated strings.


Output Format

Print the strings in their correct order, space-separated on one line.



Solution :



title-img


                            Solution in C :

In  C++  :







#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
#include<string>
#include<list>
using namespace std;


vector<string> a[100];
char str[100007];
int n,i,j,x;

int main() {
   
    
    
    cin>>n;
    for(i=0;i<n/2;i++)
    {
        cin>>x;
        cin>>str;
        a[x].push_back("-");
    
    }
    
    for(;i<n;i++)
    {
        cin>>x;
        cin>>str;
        a[x].push_back(str);
    
    }
    
    for(i=0;i<100;i++)
    {
        x=a[i].size();
        for(j=0;j<x;j++)
            cout<<a[i][j]<<" ";    
    }
    return 0;

}










In   Java  :






import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;

public class Solution {
    public static void main(String[] args) throws Exception {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(in.readLine());
        StringBuffer[] map = new StringBuffer[100];
        for(int i = 0; i < 100; i++) {
            map[i] = new StringBuffer();
        }
        for(int i = 0; i < n; i++) {
            StringTokenizer tok = new StringTokenizer(in.readLine());
            int v = Integer.parseInt(tok.nextToken());
            String s = tok.nextToken();
            map[v].append(i < n / 2 ? "-" : s).append(" ");
        }
        for(int i = 0; i < 100; i++) {
            System.out.print(map[i]);
        }
        System.out.println();
    }
}










In   C  :








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

int* hist[100];
int size[100];
int pos[100];

int main() {
    int BUF_SZ = 256;
    int N, v, i, j;
    scanf("%d", &N);
    fprintf(stderr, "%d elements\n", N);
    char *data[N];
    for (i = 0; i < N; ++i) {
        if (i < N/2) {
            data[i] = (char*)malloc(BUF_SZ*sizeof(char));
        }
        scanf("%d %s", &v, data[i<N/2?i:i-N/2]);
        if (hist[v] == NULL) {
            size[v] = 2*N/100 + 1;
            hist[v] = (int*)malloc(size[v]*sizeof(int));
        } else if (pos[v] >= size[v]) {
            size[v] *= 2;
            hist[v] = (int*)realloc(hist[v], size[v]*sizeof(int));
        }
        (hist[v])[pos[v]++] = i;
    }
    for (i = 0; i < 100; ++i) {
        fprintf(stderr, "Printing %d\n", i);
        for (j = 0; j < pos[i]; ++j) {
            if ((hist[i])[j] < N/2) {
                printf("- ");
            } else {
                printf("%s ", data[(hist[i])[j]-N/2]);
                free(data[(hist[i])[j]-N/2]);
            }
        }
        if (hist[i] != NULL) {
            free(hist[i]);
            hist[i] = NULL;
        }
    }
    return 0;
}










In   Python3  :






n = int(input())
ar = []
for i in range(0,n) :
    data = input().strip().split(' ')
    ar.append((int(data[0]), data[1]))

c = [0]*100
for a in ar :
    c[a[0]] += 1
    
c1 = [0]*100
for x in range(1,100) :
    c1[x] = c1[x-1] + c[x-1]

s = ['-']*n
for i in range(0,n) :
    if i >= n/2 :
        s[c1[ar[i][0]]] = ar[i][1]
    c1[ar[i][0]] += 1
    
print(' '.join(s))
                        








View More Similar Problems

Sparse Arrays

There is a collection of input strings and a collection of query strings. For each query string, determine how many times it occurs in the list of input strings. Return an array of the results. Example: strings=['ab', 'ab', 'abc'] queries=['ab', 'abc', 'bc'] There are instances of 'ab', 1 of 'abc' and 0 of 'bc'. For each query, add an element to the return array, results=[2,1,0]. Fun

View Solution →

Array Manipulation

Starting with a 1-indexed array of zeros and a list of operations, for each operation add a value to each of the array element between two given indices, inclusive. Once all operations have been performed, return the maximum value in the array. Example: n=10 queries=[[1,5,3], [4,8,7], [6,9,1]] Queries are interpreted as follows: a b k 1 5 3 4 8 7 6 9 1 Add the valu

View Solution →

Print the Elements of a Linked List

This is an to practice traversing a linked list. Given a pointer to the head node of a linked list, print each node's data element, one per line. If the head pointer is null (indicating the list is empty), there is nothing to print. Function Description: Complete the printLinkedList function in the editor below. printLinkedList has the following parameter(s): 1.SinglyLinkedListNode

View Solution →

Insert a Node at the Tail of a Linked List

You are given the pointer to the head node of a linked list and an integer to add to the list. Create a new node with the given integer. Insert this node at the tail of the linked list and return the head node of the linked list formed after inserting this new node. The given head pointer may be null, meaning that the initial list is empty. Input Format: You have to complete the SinglyLink

View Solution →

Insert a Node at the head of a Linked List

Given a pointer to the head of a linked list, insert a new node before the head. The next value in the new node should point to head and the data value should be replaced with a given value. Return a reference to the new head of the list. The head pointer given may be null meaning that the initial list is empty. Function Description: Complete the function insertNodeAtHead in the editor below

View Solution →

Insert a node at a specific position in a linked list

Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is e

View Solution →