Quicksort by length of String in Array - java

I have strings scanned from the user. Next step is to sort array by the length of text, I don't know what I'm doing wrong, sometimes it's working.
public static void quickSort(String[] subtitles, int start, int end) {
int i = start;
int j = end;
if (j - i >= 1) {
String pivot = subtitles[i];
while (j > 1) {
while (subtitles[i].compareTo(pivot) <= 0 && i < end && j > i)
i++;
while (subtitles[j].compareTo(pivot) >= 0 && j > start && j >= i)
j--;
if (j > i)
swap(subtitles, i, j);
}
swap(subtitles, start, j);
quickSort(subtitles, start, j - 1);
quickSort(subtitles, j + 1, end);
} else
return;
}
public static void swap(String[] a, int i, int j) {
String tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
quickSort(subtitles, 0, subtitles.length - 1);
for (int i = 0; i < subtitles.length; i++) {
System.out.print(subtitles[i] + " ");
}
Incorrect:
In:
asdzxc asd zxc
Out:
asd asdzxc zxc
Correct:
In:
sdf sdfsfwer s
Out:
s sdf sdfsfwer

Ok, I reviewed your code and made two new methods. One sorts the array alphabetically and one sorts by counting the number of letters in each word of the array. It is up to you what methods fits you well.
Tested and working.
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Subtitles {
public static void sortAlfabetical(String x[]) {
int j;
boolean found = true; // will determine when the sort is finished
String temp;
while (found) {
found = false;
for (j = 0; j < x.length - 1; j++) {
if (x[j].compareToIgnoreCase(x[j + 1]) > 0) { // ascending sort
temp = x[j];
x[j] = x[j + 1]; // swap
x[j + 1] = temp;
found = true;
}
}
}
for (int i = 0; i < x.length; i++) {
System.out.print(x[i] + " ");
}
}
public static void compare(String[] arrayOne) {
Arrays.sort(arrayOne, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return o1.length() - o2.length();
}
});
for (String s : arrayOne) {
System.out.print(s + " ");
}
}
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int amountStrings = 3;
String[] subtitles = new String[amountStrings];
System.out.println("insert ");
for (int i = 0; i < amountStrings; i++) {
subtitles[i] = scan.next();
}
System.out.println("--------");
System.out.print("Sorting alphabetical: ");
sortAlfabetical(subtitles);
System.out.println();
System.out.println("===========================");
System.out.print("Sorting by word length: ");
compare(subtitles);
}
}

Related

How to get one result out of the for statement?

import java.util.*;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
sc.close();
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input))
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
}
}
}
}
}
When I get a number input, I want to make a code that represents this number as the sum of three numbers.
The code is complete, but there are several combinations. I want to print out only one combination. How can I edit it?
First, some important suggestions:
Do not parse input inside the nested loop as it will hit the performance. Do it once outside the nested loops.
Do not close Sacnner for System.in as it also closes System.in and there is no way to open it again without restarting JVM. It means that if it is being used in some other part of your application, your application will crash.
Always follow Java naming conventions e.g. you could name numJ instead of num_j.
Coming back to your problem, there are many ways to solve it and I have listed below just a couple of them:
Use break <<label>> to exit the nested loops:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
start: for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
break start;
}
}
}
}
}
}
A sample run:
Enter a number : 123
You entered: 123
(1, 22, 100)
Put the logic in a method and return:
import java.util.Scanner;
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int num = Integer.parseInt(input);
printFirstCombination(num);
}
static void printFirstCombination(int num) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int numI = arr[i];
for (int j = i + 1; j <= 98; j++) {
int numJ = arr[j];
for (int k = j + 1; k <= 99; k++) {
int numK = arr[k];
if (numI + numJ + numK == num) {
System.out.printf("(%d, %d, %d)", numI, numJ, numK);
return;
}
}
}
}
}
}
You can create a seperate function for that and after you find a combination, print it and return there and then to the main function. In case you didn't find a combination you return 1 which can be handled in the main function,
public class Combination {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Enter a number : ");
String input = sc.next();
System.out.printf("You entered: %d\n", Integer.parseInt(input));
int res = printCombination(input);
if(res == 1) {
// Do something
}
sc.close();
}
private static int printCombination(String input) {
int[] arr = new int[100];
for (int i = 0; i < arr.length; i++) {
arr[i] = i + 1;
}
for (int i = 0; i <= 97; i++) {
int num_i = arr[i];
for (int j = i + 1; j <= 98; j++) {
int num_j = arr[j];
for (int k = j + 1; k <= 99; k++) {
int num_k = arr[k];
if (num_i + num_j + num_k == Integer.parseInt(input)) {
System.out.printf("(%d, %d, %d)", num_i, num_j, num_k);
return 0;
}
}
}
}
return 1;
}
}

ArraySort not displaying?

It is not giving any output but the code runs without error.I wanted to show all the methods including the result for bubble sort, selection sort and compare sort? How do I call the methods. When I run it, it is not giving me any output. So, I just needed help to run the code.
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
}
//get a random number;
private int getRand() {
Random in = new Random();
return in.nextInt(100);
}
//fill an array with numbers from 0 to 99;
public static void fillArray(int[] array) {
for (int i = 0; i < array.length; i++) {
array[i] = i;
}
}
//copy an array to another;
public static void copyArray(int[] aArray, int[] bArray) {
for (int i = 0; i < aArray.length; i++) {
bArray[i] = aArray[i];
}
}
//swap two numbers in an array according to index;
private void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
//random select two numbers in an array and switch them;
int disorderArray(int[] array) {
int i, j;
i = getRand();
j = getRand();
swap(array, i, j);
//System.out.println("the index of the 2 swapped numbers are " + i + " " +
j
);
return i;
}
//print out the array;
public static void printArray(int[] array, int col) {
for (int i = 0; i < array.length - col + 1; i += col) {
for (int j = i; j < i + col; j++)
System.out.print("number " + j + " is " + array[j] + "; ");
System.out.println();
}
for (int i = array.length - array.length % col; i < array.length; i++)
System.out.print("number " + i + " is " + array[i] + "; ");
System.out.println();
System.out.println();
}
//bubble sort;
public void bubbleSort(int[] array) {
for (int i = array.length - 1; i > 0; i--) {
for (int j = 0; j < i; j++) {
if (array[j] > array[j + 1])
swap(array, j, j + 1);
}
}
}
//selection sort;
public void selectionSort(int[] array) {
for (int i = 0; i < array.length - 1; i++) {
int p = i;
for (int j = i + 1; j < array.length; j++)
if (array[p] > array[j])
p = j;
if (i != p)
swap(array, i, p);
}
}
//compare two arrays;
public static boolean compareArrays(int[] aArray, int[] bArray) {
boolean s = true;
int i = 0;
if (aArray.length == bArray.length) {
while (s && i < aArray.length) {
if (aArray[i] != bArray[i])
s = false;
i++;
}
}
return s;
}
}
You have implemented some methods, but you need to invoke them from your main method, e.g.
public static void main(String[] args) {
int[] A = new int[100];
int[] B = new int[100];
fillArray(A);
// more method calls...
}
Note, you have implemented both class (static) methods and instance (non-static) methods. The semantics for how you call them differs. If your program is is implemented in a class named Foo, you can write the following:
// method call to class method
Foo.fillArray();
// method call to instance metod requires an instance
Foo fooInstance = new Foo();
int randomNumber = fooInstance.getRand();
Normally, you use instance methods to manipulate instance variables and class methods to manipulate class variables or more commonly as helper methods that do not involve state at all. More information regarding this can be found in the Understanding Class Members chapter of Oracle's Java Tutorial (scroll down to Class Methods).

Sorting an array of string data using the insertion sort method

I'm having trouble using insertion to sort an array of strings.
When I compile the following code:
public class Project1 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
String names[]=new String[5];
int size=names.length;
System.out.println("Enter the 5 car manufacturers: ");
//Load Array
for (int i = 0; i < 5; i++) {
names[i] = input.nextLine();
}
//Print descending order list
String[] descSort;
descSort=bubbleSortDesc(names);
System.out.println("Car manufacturers listed sorted in descending order (via BubbleSort): ");
for (int x=0; x < names.length; x++) {
System.out.println(names[x]);
}
//Print ascending order list
insertionSortAsc(names, size);
System.out.println("Car manufacturers listed sorted in ascending order (via InsertionSort): ");
for (int z=0; z < names.length; z++) {
System.out.println(names[z]);
}
}ยจ
public static String[] bubbleSortDesc(String[] names) {
String temp;
int passNum, i, result;
for (passNum=1; passNum <= 4; passNum++) {
for (i = 0; i<=(4-passNum); i++) {
result=names[i].compareToIgnoreCase(names[i+1]);
if(result<0) {
temp=names[i];
names[i]=names[i+1];
names[i+1]=temp;
}
}
}
return names;
}
public static void insertionSortAsc(String[] names, int i) {
String temp = names[i];
int j = i-1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0) {
names[j+1]=names[j];
j--;
}
names[j+1]=temp;
}
public static void insertionSort(String[] names, int n) {
for(int i = 1; i<n; i++) {
insertionSortAsc(names, i);
}
}
}
It gives me the error:
cannot find symbol- method insert(java.lang.String[], int)
I suspect it has something to do with the fact that we were told to use our book as reference for the code, yet the book only deals with sorting data of type int and there are no examples for sorting string data.
Any help is appreciated.
Edit: After fixing the error, the program compiles and executes but after inputting the data it crashes and gives me the following error
java.lang.ArrayIndexOutofBoundsException:
5
This error highlights the line String temp = names[i]
You haven't defined a method named insert.
This will work the way you intend:
public static void insertionSortAsc(String[] names, int n)
{
for(int i = 1; i<n; i++)
{
insert(names, i);
}
}
public static void insert(String[] names, int i)
{
String temp = names[i];
int j = i - 1;
while (j >= 0 && names[j].compareToIgnoreCase(temp) > 0)
{
names[j + 1]= names[j];
j--;
}
names[j + 1] = temp;
}
public static void insertionSort(int... arr) {
for (int i = 1; i < arr.length; i++) {
if (arr[i] >= arr[i - 1])
continue;
int j = i - 1;
for (; j >= 0; j--)
if (arr[j] < arr[i])
break;
int tmp = arr[i];
System.arraycopy(arr, j + 1, arr, j + 2, i - j - 1);
arr[j + 1] = tmp;
}
}

Quick Sort algorithm not working properly

I have created a code for quick sorting the only problem is that sometimes it gives out the sorted array and sometimes it doesn't. Any idea as to why it would do that? The first part of always works obviously.. the part where it shows the array TO BE sorted but the next part shows up occasionally after I run it a lot of time.
This is part of my code:
public static final int max = 10;
public static void main(String[] args) {
int[] toSortArray = new int[max];
for (int i = 0; i < max; i++) {
toSortArray[i] = (int) (Math.random() * 100);
}
System.out.println("The array to be sorted is:");
for (int i = 0; i < max; i++) {
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
// Beginning of the algorithm
quicksortHelper(toSortArray, 0, max - 1);
// End of the algorithm
System.out.println("The sorted array is: ");
for (int i = 0; i < max; i++) {
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
}
private static void quicksortHelper(int[] toSortArray, int first, int last) {
if (first < last) {
int splitpoint = partition(toSortArray, first, last);
quicksortHelper(toSortArray, first, splitpoint - 1);
quicksortHelper(toSortArray, splitpoint + 1, last);
}
}
private static int partition(int[] toSortArray, int first, int last) {
int pivot = toSortArray[first];
int leftmark = first + 1;
int rightmark = last;
boolean done = true;
while (done) {
while (leftmark <= rightmark && toSortArray[leftmark] < pivot) {
leftmark++;
}
while (leftmark <= rightmark && toSortArray[rightmark] > pivot) {
rightmark--;
}
if (leftmark > rightmark) {
done = false;
} else {
int temp = toSortArray[leftmark];
toSortArray[leftmark] = toSortArray[rightmark];
toSortArray[rightmark] = temp;
}
}
int temp = toSortArray[rightmark];
toSortArray[rightmark] = toSortArray[first];
toSortArray[first] = temp;
return rightmark;
}
This is a program that I have written from your code and it works great
class QuickSort{
public static final int max = 10;
public static void main(String[] args) {
int[] toSortArray = new int[max];
for (int i = 0; i < max; i++) {
toSortArray[i] = (int) (Math.random() * 100);
}
System.out.println("The array to be sorted is:");
for (int i = 0; i < max; i++) {
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
// Beginning of the algorithm
quicksortHelper(toSortArray, 0, max - 1);
// End of the algorithm
System.out.println("The sorted array is: ");
for (int i = 0; i < max; i++) {
System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");
}
private static void quicksortHelper(int[] toSortArray, int first, int last) {
if (first < last) {
int splitpoint = partition(toSortArray, first, last);
quicksortHelper(toSortArray, first, splitpoint - 1);
quicksortHelper(toSortArray, splitpoint + 1, last);
}
}
private static int partition(int[] array, int first, int last) {
int temp;
// Always assumes pivot index is first
int pivot = array[first];
// Swap Pivot and Last
array[first] = array[last];
array[last] = pivot;
int mark = first;
for(int i=first;i<last;i++){
if(array[i] <= pivot){
temp = array[mark];
array[mark] = array[i];
array[i] = temp;
mark++;
}
}
temp = array[last];
array[mark] = array[last];
array[last] = temp;
return mark;
}
}
Try changing either
while (leftmark <= rightmark && toSortArray[leftmark] < pivot) {
leftmark++;
}
to
while (leftmark <= rightmark && toSortArray[leftmark] <= pivot) {
leftmark++;
}
or,
while (leftmark <= rightmark && toSortArray[rightmark] > pivot) {
rightmark--;
}
to
while (leftmark <= rightmark && toSortArray[rightmark] >= pivot) {
rightmark--;
}
(That is, change the < to <= or > to >=.)
This will ensure that it doesn't quit when it comes to a non-unique value.

Generating permutations of an int array using java -- error

I am writing a JAVA code to generate all permutations of a integer array.
Though I am getting the number of permutations right, the permutations themselves are not correct.
On running I obtain:
Input array Length
3
1
2
3
0Permutation is
1, 2, 3,
##########################
1Permutation is
1, 3, 2,
##########################
2Permutation is
3, 1, 2,
##########################
3Permutation is
3, 2, 1,
##########################
4Permutation is
1, 2, 3,
##########################
5Permutation is
1, 3, 2,
##########################
6 number of permutations obtained
BUILD SUCCESSFUL (total time: 3 seconds)
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
int temp=input[i];
input[i]=input[startindex];
input[startindex]=temp;
Permute(input, startindex+1);
You've swapped an element before calling Permute but you need to swap it back again afterwards to keep consistent positions of elements across iterations of the for-loop.
This is the best solution I have seen so far :
public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6 };
permute(0, a);
}
public static void permute(int start, int[] input) {
if (start == input.length) {
//System.out.println(input);
for (int x : input) {
System.out.print(x);
}
System.out.println("");
return;
}
for (int i = start; i < input.length; i++) {
// swapping
int temp = input[i];
input[i] = input[start];
input[start] = temp;
// swap(input[i], input[start]);
permute(start + 1, input);
// swap(input[i],input[start]);
int temp2 = input[i];
input[i] = input[start];
input[start] = temp2;
}
}
check this out
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
//This will give correct output
import java.util.Scanner;
public class PermulteArray {
public static int counter = 0;
public static void Permute(int[] input, int startindex) {
int size = input.length;
if (size == startindex + 1) {
System.out.println(counter + "Permutation is");
for (int i = 0; i < size; i++) {
System.out.print(input[i] + ", ");
}
System.out.println();
System.out.println("##########################");
counter++;
} else {
for (int i = startindex; i < size; i++) {
int temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
Permute(input, startindex + 1);
temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
}
}
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
System.out.println("Input array Length");
int arraylength = in.nextInt();
int[] input = new int[arraylength];
for (int i = 0; i < arraylength; i++) {
input[i] = in.nextInt();
}
counter = 0;
Permute(input, 0);
System.out.println(counter + " number of permutations obtained");
}
}
You can solve this using recursive calls.
https://github.com/Pratiyush/Master/blob/master/Algorithm%20Tutorial/src/arrays/Permutations.java
public void swap(int[] arr, int i, int j)
{
int tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
public void permute(int[] arr, int i)
{
if (i == arr.length)
{
System.out.println(Arrays.toString(arr));
return;
}
for (int j = i; j < arr.length; j++)
{
swap(arr, i, j);
permute(arr, i + 1); // recurse call
swap(arr, i, j); // backtracking
}
}
public static void main(String[] args) {
Permutations permutations = new Permutations();
int[] arr = {1, 2, 3,4};
permutations.permute(arr, 0);
}
Also, other approaches are available in
http://www.programcreek.com/2013/02/leetcode-permutations-java/
http://www.programcreek.com/2013/02/leetcode-permutations-ii-java/
public class PermuteArray {
public static void permute(char[] input2, int startindex) {
if (input2.length == startindex) {
displayArray(input2);
} else {
for (int i = startindex; i < input2.length; i++) {
char[] input = input2.clone();
char temp = input[i];
input[i] = input[startindex];
input[startindex] = temp;
permute(input, startindex + 1);
}
}
}
private static void displayArray(char[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + "; ");
}
System.out.println();
}
public static void main(String[] args) {
char[] input = { 'a', 'b', 'c', 'd'};
permute(input, 0);
}
}
import java.util.ArrayList;
public class RecursivePermGen {
void permGen(int n, int m, ArrayList<Integer> cur) {
if(m == 0) {
System.out.println(cur);
return;
}
for(int i = 1; i <= n; i++) {
cur.add(0, i);
permGen(n, m-1, cur);
cur.remove(0);
}
}
public static void main(String[] args) {
RecursivePermGen pg = new RecursivePermGen();
ArrayList<Integer> cur = new ArrayList<Integer>();
pg.permGen(2, 2, cur);
}
}
I have simple answer for this question, you can try with this.
public class PermutationOfString {
public static void main(String[] args) {
permutation("123");
}
private static void permutation(String string) {
printPermutation(string, "");
}
private static void printPermutation(String string, String permutation) {
if (string.length() == 0) {
System.out.println(permutation);
return;
}
for (int i = 0; i < string.length(); i++) {
char toAppendToPermutation = string.charAt(i);
String remaining = string.substring(0, i) + string.substring(i + 1);
printPermutation(remaining, permutation + toAppendToPermutation);
}
}
}
A solution i have used several times (mostly for testing purposes) is in the following gist. It is based on the well-known algorithm to generate permutations in lexicographic order (no recursion):
/**
* Compute next (in lexicographic order) permutation and advance to it.
*
* Find greater index i for which a j exists, such that:
* j > i and a[i] < a[j] (i.e. the 1st non-inversion).
* For those j satisfying the above, we pick the greatest.
* The next permutation is provided by swapping
* items at i,j and reversing the range a[i+1..n]
*/
void advanceToNext() {
// The array `current` is the permutation we start from
// Find i when 1st non-inversion happens
int i = n - 2;
while (i >= 0 && current[i] >= current[i + 1])
--i;
if (i < 0) {
// No next permutation exists (current is fully reversed)
current = null;
return;
}
// Find greater j for given i for 1st non-inversion
int j = n - 1;
while (current[j] <= current[i])
--j;
// Note: The range a[i+1..n] (after swap) is reverse sorted
swap(current, i, j); // swap current[i] <-> current[j]
reverse(current, i + 1, n); // reverse range [i+1..n]
}
A complete solution (in the form of a class) lies here:
https://gist.github.com/drmalex07/345339117fef6ca47ca97add4175011f

Categories