83.1k views
4 votes
Implement (in Java) the radixSort algorithm to sort in increasing order an array of integer positive keys. public void radixSort(int arr[]) In your implementation you must consider that each key contains only even digits (0, 2, 4, 6, and 8). Your program must detect the case of odd digits in the keys, and, in this case, abort. Example #1:

1 Answer

6 votes

Answer:

see explaination

Step-by-step explanation:

import java.util.Scanner;

import java.util.ArrayList;

public class EvenRadixSort {

public static void main(String[] args) {

int n;

Scanner s=new Scanner(System.in);

System.out.println("enter number of elements to sort");

n=s.nextInt();

int[] arr=new int[n];

System.out.println("enter elements");

for(int i=0;i<n;i++)

arr[i]=s.nextInt();

radixsort(arr);

System.out.print("after sorting\t ");

for(int i=0;i<n;i++)

System.out.print(arr[i]+" ");

System.out.print("\\");

}

public static void radixsort(int[] arr) {

ArrayList<Integer>[] buckets = new ArrayList[10];

for (int i = 0; i < buckets.length; i++) {

buckets[i] = new ArrayList<Integer>();

}

// sort

boolean flag = false;

int tmp = -1, divisor = 1;

while (!flag) {

flag = true;

// split input between lists

for(int i=0;i<arr.length;i++) {

tmp = arr[i] / divisor;

if(tmp%2!=0){

System.out.println("odd digit in key");

System.exit(0);

}

buckets[tmp % 10].add(arr[i]);//insert number in certain bucket

if (flag && tmp > 0) {// check for divisor increment for next digit

flag = false;

}

}

// empty lists into input array arr

int a = 0;

for (int b = 0; b < 10; b=b+2) {

for (Integer i : buckets[b]) {

arr[a++] = i;

}

buckets[b].clear();

}

// move to next digit

divisor *= 10;

}

}

}

see attachment

User Ricardo Gaefke
by
5.0k points