In: Computer Science
What would the code look like if you weren't using hash maps and array lists (only using scanner import) and solving using a partition algorithm?
partition algorithm:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int f = sc.nextInt();
int[] ar = new int[f];
for (int i = 0; i < f; i++) {
ar[i] = sc.nextInt();
}
sc.close();
partition(ar);
printAr(ar);
}
public static int partition(int [] ar) {
int pivotIndex = 0;
int pivotValue = ar[pivotIndex];
swap(ar, pivotIndex, ar.length - 1);
int indexToReturn = 0;
for (int i = 0; i < ar.len; i++){
if (ar[i] < pivotValue){
swap(ar, i, indexToReturn);
indexToReturn++;
}
}
swap(ar, indexToReturn, ar.length - 1);
return indexToReturn;
}
private static void swap(int [] ar, int i, int j) {
int temp = ar[i];
ar[i] = ar[j];
ar[j] = temp;
}
private static void printAr(int[] ar) {
for (int num: ar) {
System.out.print(num + " ");
}
System.out.println();
}
}
this is how an partition algorithm looks like without using hash maps and array lists.