1.Implement and test the Counting Sort.
2.Implement and test the Radix Sort using Binary code.
3.Implement a stack on the basis of an array with consideration of overflow and underflow.
package homework4;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class MainTest {
public static void main(String[] args)
{
//第一题 CountingSort
int[] a = new int[] {2,3,4,2,6,7,9,3,2,2};
int[] b = new int[11];
CountingSort(a,b);
System.out.println(Arrays.toString(b));
//第二题 RadixSort Binary
int[] c =new int[] {22,21,43,76,45,78,7,9,3,2};
RadixSort(c);
System.out.println(Arrays.toString(c));
// //第三题 Stack
Stack stack = new Stack(10);
try
{
stack.push(10);
stack.pop(9);
}catch(Exception e) {
e.printStackTrace();
}
}
public static void CountingSort(int[] A , int[] B ) {
int k = 0;
for(int i = 0 ; i < A.length ; i++)
{
if(A[i] > k)
k = A[i];
}
int[] C = new int[k + 1];
for(int i = 1 ; i <= k ; i++)
C[i] = 0;
for(int j = 0 ; j <= A.length - 1 ; j++)
C[A[j]] = C[A[j]] + 1;
for(int i = 1 ; i <= k ; i++)
C[i] = C[i] + C[i-1];
for(int j = A.length - 1 ; j >= 0 ; j--)
{
B[C[A[j]]] = A[j];
C[A[j]] = C[A[j]] - 1;
}
}
private static void RadixSort(int[] data)
{
for(int i = 0 ; i < 32 ; i++)
{
ArrayList<Integer> l0 = new ArrayList<>();
ArrayList<Integer> l1 = new ArrayList<>();
for(int x = 0 ; x < data.length ; x++) {
if((data[x] >> i&1) == 0)
l0.add(data[x]);
else l1.add(data[x]);
}
for(int j = 0 ; j < l0.size() ; j++)
data[j] = l0.get(j);
for(int j = 0 ; j < l1.size() ; j++)
data[j + l0.size()] = l1.get(j);
}
}
}
class Stack
{
private int top;
private int[] data;
public Stack(int maxSize){
data = new int[maxSize];
top = -1;
}
void push(int x) throws Exception{
if(top == data.length - 1)
throw new Exception("The Stack is Overflow.");
else data[++top] = x;
}
int pop(int x) throws Exception{
if(top == -1)
throw new Exception("The Stack is Underflow.");
else {
top--;
return data[top + 1];
}
}
}