0% found this document useful (0 votes)
86 views7 pages

Lab CS213 - 21 03 2023 PDF

The document describes an algorithm for sorting an array of strings using MSD Radix Sort. It begins by partitioning the array into buckets based on the first character of each string. It then recursively sorts the strings in each bucket by the next character, continuing this process until all strings are sorted based on each character from first to last. This algorithm runs in O(N + MB) time and space, where N is the number of strings, M is the maximum length of a string, and B is the size of the character set being used (typically 256). An implementation in Java is also provided.

Uploaded by

Jaya Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
86 views7 pages

Lab CS213 - 21 03 2023 PDF

The document describes an algorithm for sorting an array of strings using MSD Radix Sort. It begins by partitioning the array into buckets based on the first character of each string. It then recursively sorts the strings in each bucket by the next character, continuing this process until all strings are sorted based on each character from first to last. This algorithm runs in O(N + MB) time and space, where N is the number of strings, M is the maximum length of a string, and B is the size of the character set being used (typically 256). An implementation in Java is also provided.

Uploaded by

Jaya Agarwal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

1.

Maximum Gap
Given an integer array nums, return the maximum difference between two
successive elements in its sorted form. If the array contains less than two elements,
return 0.

You must write an algorithm that runs in linear time and uses linear extra space.

Input: First line takes a positive integer n as input. Second line takes n space
separated integer as input for the array.
Output: Integer representing maximum difference.

Example
Input: 4
3691
Output:3
Explanation: The sorted form of the array is [1,3,6,9], either (3,6) or (6,9) has the
maximum difference 3.

Input: 1
5
Output:0
Explanation: The array contains less than 2 elements, therefore return 0

Algorithm
Use the linear time sorting technique with linear extra space and then find out the
maximum difference between two consecutive elements.

1. The first step is to find the maximum value in nums array, it will
be the threshold to end the loop.
2. Then use the radix sort algorithm to sort based on each digit from Least
Significant Bit(LSB) to Most Significant Bit (MSB),
3. Finally, find the maximum gap from the sorted array.

Time and space complexities are both O(n).


Algorithm for Radix Sort
The idea of Radix Sort is to do digit by digit sort starting from least significant
digit to most significant digit. Radix sort uses counting sort as a subroutine to sort.

1. radixSort(arr)
2. max = largest element in the given array
3. d = number of digits in the largest element (or, max)
4. Now, create d buckets of size 0 - 9
5. for i -> 0 to d
6. sort the array elements using counting sort (or any stable sort) according to
the digits at the ith place

2. Sort the array of strings using MSD Radix Sort.


Given an array of strings, sort the array in ascending order(lexicographically) using
MSD Radix Sort.

Input: First line takes a positive integer n as input. Second line takes n space
separated strings as input for the array.
Output: Sorted array in ascending order.

Example:
Input:12
dab add cab fad fee bad dad bee fed bed ebb ace
Output:ace add bad bed bee cab dab dad ebb fad fed fee
Explanation
The main idea is
● Partition the array into R pieces according to the first character(use key-
indexed counting).
● Recursively sort all strings that start with each character(key-indexed counts
delineate subarrays to sort
Algorithm

radixMSD(int * items, int left, int right, int * scratch, int digit_position)
1. If the digit position is greater than the number of digits in the items,
return.
2. If right <= left, return.
3. Count the number of items for each bucket.
4. Figure out where each bucket should be stored (positions of the first and last
element of the bucket in the scratch array).
5.Copy each item to the corresponding bucket (in the scratch array).
6. Copy the scratch array back into items.
7.For each bucket:
8. • new_left = leftmost position of bucket in items
9. • new_right = rightmost position of bucket in items
10. • radixMSD(items, new_left, new_right, scratch, digit_position+1)

MSD Radix sort takes O(N + MB), where M = length of the longest string and B =
size of radix (B=10 possible numbers or B=256 characters or B=2 for Binary).
#include <stdio.h>
#include <string.h>

int main ()
{
char buf[] ="abc qwe ccd";
int i = 0;
char *p = strtok (buf, " ");
char *array[3];

while (p != NULL)
{
array[i++] = p;
p = strtok (NULL, " ");
}

for (i = 0; i < 3; ++i)


printf("%s\n", array[i]);

return 0;
}
// Java program for the above approach
import java.io.*;
import java.lang.*;
import java.util.*;

public class Main {

// Utility function to get the ASCII


// value of the character at index d
// in the string
static int charAt(String str, int d)
{
if (str.length() <= d)
return -1;
else
return (int)(str.charAt(d));
}

// Function to sort the array using


// MSD Radix Sort recursively

// Function to print an array


static void print(String str[], int n)
{
for (int i = 0; i < n; i++) {
System.out.print(str[i] + " ");
}
System.out.println();
}
private static void sort(String[] a, String[] aux, int lo, int hi, int d)
{
System.out.print("lo="+lo+" hi="+hi);
if (hi <= lo) return;
int R=255;
int[] count = new int[R+2];
for (int i = lo; i <= hi; i++)
count[charAt(a[i], d) + 2]++;
for (int r = 0; r < R+1; r++)
count[r+1] += count[r];
for (int i = lo; i <= hi; i++)
aux[count[charAt(a[i], d) + 1]++] = a[i];
for (int i = lo; i <= hi; i++)
a[i] = aux[i - lo];
for (int r = 0; r < R; r++)
sort(a, aux, lo + count[r], lo + count[r+1] - 1, d+1);
}
// Driver Code
public static void main(String[] args)
{
// Input String
String str[] = { "midnight", "badge", "bag",
"worker", "banner", "wander" };

// Size of the string


int n = str.length;

System.out.print("Unsorted array : ");

// Print the unsorted array


print(str, n);
String[] aux = new String[n];
sort(str, aux, 0, n-1, 0);

System.out.print("Sorted array : ");

// Print the sorted array


print(str, n);
}
}

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy