Java: Permutation of array - java

I'm not very familiar with recursion in Java. I'm trying to write a method that calculates all the permutations of an array of integers. I need to modify the following perfectly working method so that, instead of printing to screen all the permutations of an array, it inserts them in a bidimensional array. So the input of the method is the array of n integers and the output is a bidimensional array with n! rows and n columns. The program I need to modify is this:
public static void permute(int[] array, int k)
{
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
Array.printValues(array);
}
}
So, what I need is something like this:
public static int[][] permute(int[] array, int k)
{
//code here
}
Thank you.

Stick them in a list and then get an array out of it. You could go directly with an int[][] but you do not know the first dimension value without an extra repetition.
public static int[][] permuteToArray(int[] array, int k){
ArrayList<int[]> arrL=new ArrayList<>();
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1, arrL);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
arrL.add(array);
}
return arrL.toArray(new int[][]);
}
Change permute( to be:
public static void permute(int[] array, int k, ArrayList arrL) //raw type, I know
{
for(int i=k; i<array.length; i++)
{
int temp;
temp = array[i];
array[i] = array[k];
array[k] = temp;
permute(array, k+1);
int temp2;
temp2 = array[i];
array[i] = array[k];
array[k] = temp2;
}
if (k == array.length-1)
{
arrL.add(array);
}
}

public static void _permute(ArrayList<ArrayList<Integer>> res, ArrayList<Integer> cur, int k, boolean[] status, int[] array)
{
if (cur.size() == k) {
res.add((ArrayList<Integer>)cur.clone());
return;
}
for (int i = 0; i < k; i++)
{
if (status[i]) continue;
cur.add(array[i]);
status[i] = true;
_permute(res, cur, k, status, array);
status[i] = false;
cur.remove(new Integer(array[i]));
}
}
public static ArrayList<ArrayList<Integer>> permute(int[] array, int k)
{
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
ArrayList<Integer> cur = new ArrayList<Integer>();
boolean[] status = new boolean[k];
for (int i = 0; i < k; i++)
{
status[i] = false;
}
_permute(res, cur, k, status, array);
return res;
//code here
}
You can get all permutation of array in array list. I think you can extract array from the list yourself. And be careful, this function can remove duplication if there're same numbers in original array.

public static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void permute(int[] array, List<int[]> cache, int k)
{
if (k == array.length-1)
{
cache.add(array.clone()); //use clone, or you will get the same int array
return;
}
for(int i=k; i<array.length; i++)
{
swap(array, i,k);
permute(array, cache, k+1);
swap(array, i, k);
}
}

I can give you an example recursive algorith of permutation.
It is based on the fact that permutation of n elements is based on permutation of n-1 elements.
import java.util.ArrayList;
import java.util.List;
class Permutation {
public static void main(String[] args) {
List<Object> input = new ArrayList<>();
input.add(1);
input.add(2);
input.add(3);
print(permutation(input));
}
public static void print(List<List<Object>> list) {
for (List<Object> objects : list) {
System.out.println(objects);
}
}
public static List<List<Object>> permutation(List<Object> input) {
if (input.isEmpty()) {
throw new IllegalStateException();
}
// This is end condition for recursion
if (input.size() == 1) {
List<List<Object>> result = new ArrayList<>();
result.add(input);
return result;
}
return merge(input.get(0), permutation(input.subList(1, input.size())));
}
private static List<List<Object>> merge(Object o, List<List<Object>> input) {
List<List<Object>> result = new ArrayList<>();
int inputSize = input.get(0).size();
for (int i = 0; i < inputSize + 1; i++) {
for (List<Object> oneRow : input) {
// copy the row and insert additional element
List<Object> oneRowExpanded = new ArrayList<>();
oneRowExpanded.addAll(oneRow);
oneRowExpanded.add(i, o);
result.add(oneRowExpanded);
}
}
return result;
}
}
This will print the following:
[1, 2, 3]
[1, 3, 2]
[2, 1, 3]
[3, 1, 2]
[2, 3, 1]
[3, 2, 1]

Related

MergeSort problems parameters

import java.lang.reflect.Array;
public class Sorting {
public static void mergeSort(CompareInt[] arr) {
for(int i=0;i<=arr.length-1;i++){
System.out.println("Initial Arr element:"+arr[i].val);
}
CompareInt[] arrAux;
arrAux = new CompareInt[arr.length];
mergeS(arr,0,arr.length-1,arrAux);
}
public static void mergeS(CompareInt[] arr,int startI,int endI,CompareInt[] arrAux){
//System.out.println("StartIndex:"+startI+" EndIndex:"+endI);
if(endI-startI<=0)
return;
int mid = (startI+endI)/2;
// System.out.println("Midpoint value:"+mid);
mergeS(arr,startI,mid);
mergeS(arr,mid+1,endI);
// System.out.println("Inside mergeS");
// System.out.println("StartIndex:"+startI+" EndIndex:"+endI+" Midpoint value:"+mid);
// System.out.println("Arr length:"+arr.length);
arrAux = merge(arr,mid);
for(int i=0;i<=arr.length-1;i++){
arr[i]=arrAux[i];
System.out.println("Arr element:"+arr[i].val);
}
}
public static CompareInt[] merge(CompareInt[] arr,int midpoint){
int i=0,j=0,k=0;
int n1 = arr.length-midpoint;
int n2 = arr.length-n1;
//System.out.println("Midpoint value inside merge:"+midpoint);
//System.out.println("N1:"+n1+" N2:"+n2);
CompareInt[] L;
CompareInt[] R;
CompareInt[] resA;
L = new CompareInt[n1];
R = new CompareInt[n2];
resA = new CompareInt[n1+n2];
for(i=0;i<n1;i++){
L[i]=arr[i];
// System.out.println("Inside Left loop"+i);
// System.out.println(L[i].val);
}
for(j=0;j<n2;j++){
R[j]=arr[midpoint+j+1];
// System.out.println("Inside Right loop "+j);
// System.out.println(R[j].val);
}
i=0;
j=0;
k=0;
while(i<n1 && j<n2){
if(L[i].compareTo(R[j])<=0){
resA[k]=L[i];
// System.out.println(resA[i].val);
i++;
}
else{
resA[k]=R[j];
// System.out.println(resA[j].val);
j++;
}
k++;
}
while(i<n1){
resA[k]=L[i];
//System.out.println(resA[k].val);
i++;
k++;
}
while(j<n2){
resA[k]=R[j];
//System.out.println(resA[k].val);
j++;
k++;
}
return resA;
}
}
I am getting actual and formal argument lists differ in length at line mereS(..)
How do I solve this error and is there any way to run with different number of arguments in actual and formal parameters.
This is how Pseudo code is given ..
Modifications in pseudo code:
if (hi - lo <= 0)", not "if (hi - lo <= 1)".
aux <- merge(A[lo:mid], A[mid+1:hi])
This code will sort out your problem :
public static void main(String[] args) {
int arr[] = {12, 11, 13, 5, 6, 7};
System.out.println("\nSorted array");
for(int i=0;i<=arr.length-1;i++){
System.out.println("Initial Arr element:"+arr[i]);
}
mergeS(arr, 0, arr.length-1);
System.out.println("\nSorted array");
for(int i=0;i<=arr.length-1;i++){
System.out.println("Sorted Arr element:"+arr[i]);
}
}
public static void mergeS(int[] arr,int startI,int endI){
//System.out.println("StartIndex:"+startI+" EndIndex:"+endI)
if (startI< endI)
{
// Find the middle point
int m = (startI+endI)/2;
// Sort first and second halves
mergeS(arr,startI, m);
mergeS(arr , m+1, endI);
// Merge the sorted halves
merge(arr, startI,m, endI);
}
}
public static void merge(int arr[], int startI, int midpoint, int endI){
// Find sizes of two subarrays to be merged
int n1 = midpoint - startI + 1;
int n2 = endI - midpoint;
/* Create temp arrays */
int L[] = new int [n1];
int R[] = new int [n2];
/*Copy data to temp arrays*/
for (int i=0; i<n1; ++i)
L[i] = arr[startI + i];
for (int j=0; j<n2; ++j)
R[j] = arr[midpoint + 1+ j];
/* Merge the temp arrays */
// Initial indexes of first and second subarrays
int i = 0, j = 0;
// Initial index of merged subarry array
int k = startI;
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
k++;
}
/* Copy remaining elements of L[] if any */
while (i < n1)
{
arr[k] = L[i];
i++;
k++;
}
/* Copy remaining elements of R[] if any */
while (j < n2)
{
arr[k] = R[j];
j++;
k++;
}
}

Java Integer Array Rotation (Left)

I have a simple rotation function which takes an array and a number to rotate the numbers left
e.g. [1,2,3,4,5] & 2 - output: [3,4,5,1,2].
I want to know the most efficient way of completing this function, whether it would be to convert the int array into a string a splice it or whether to copy the array or to convert to an List<Integer>.
If anyone wants additional information please ask!
my solution at the moment:
static int[] rotLeft(int[] a, int d) {
int lengthOfArray = a.length;
int[] temp = new int[lengthOfArray];
for(int i = 0; i < lengthOfArray; i++){
int newLocation = (i + (lengthOfArray - d)) % lengthOfArray;
temp[newLocation] = a[i];
}
return temp;
}
Simple way to do it with O(n) complexity is as below along with handling of valid shifts int[] arr: is an int array, n=length of an array, d=how many shifts required.
public int[] leftRotate(int[] arr, int n, int d) {
int rot = 0;
int[] marr = new int[n];
if (d < 0 || d == 0 || d>n) {
return arr;
}
else {
for (int i = 0; i < n; i++) {
if (i < n - d) {
marr[i] = arr[i + d];
} else {
marr[i] = arr[rot];
rot++;
}
}
return marr;
}
}
public void GetArray(int[] arr, int n, int d) {
int[] arr1 = leftRotate(arr, n, d);
for (int j : arr1) {
System.out.println(j);
}
}
public static void main(String args[]) {
int[] arr = { 1,2,3,4,5 };
int n = arr.length;
Test2 obj = new Test2();
obj.GetArray(arr, n, 2);
}
Why don't you try this one
void Rotate(int arr[], int d, int n)
{
for (int i = 0; i < d; i++)
leftRotatebyOne(arr, n);
}
void leftRotatebyOne(int arr[], int n)
{
int i, temp;
temp = arr[0];
for (i = 0; i < n - 1; i++)
arr[i] = arr[i + 1];
arr[i] = temp;
}
and to call this invoke method like below
int arr[] = { 1, 2, 3, 4, 5 };
Rotate(arr, 2, 5);

Ordered Sampling with Replacement

Im really stuck in a rut for this one.
I want generate all the combinations such that there is Ordered Sampling with Replacement (i think this is what its called, see my example) and the result is output in an array of arrays (2D array).
For example
public static int[][] combinations(int n, int k)
on input n=3, k=2 would give:
[[0,0],[0,1],[0,2],[1,0],[1,1],[1,2],[2,0],[2,1],[2,2]]
I'm really unsure how to do this efficiently. Any pointers are appreciated!
Here we have a set with n elements and we want to draw k samples from the set such that ordering matters and repetition is allowed.
Here the code:
public static void main(String[] args) {
int n = 4;
int k = 2;
int[][] result = combinations(n, k);
System.out.println(Arrays.deepToString(result));
//this will print:
//[[0,0],[0,1],[0,2],[0,3],[1,0],[1,1],[1,2],[1,3],[2,0],[2,1],[2,2],[2,3],[3,0],[3,1],[3,2],[3,3]]
}
public static int[][] combinations(int n, int k) {
int[] nArray = IntStream.range(0, n).toArray();
List<String> list = new ArrayList<String>();
combinationStrings(k, nArray, "", list);
return fromArrayListToArray(list, k);
}
private static void combinationStrings(int k, int[] nArray, String currentString, List<String> list) {
if (currentString.length() == k) {
list.add(currentString);
} else {
for (int i = 0; i < nArray.length; i++) {
String oldCurrent = currentString;
currentString += nArray[i];
combinationStrings(k, nArray, currentString, list);
currentString = oldCurrent;
}
}
}
private static int[][] fromArrayListToArray(List<String> list, int k) {
int[][] result = new int[list.size()][k];
for (int i=0;i<list.size();i++) {
String[] split = list.get(i).split("\\B");
for (int j = 0; j < split.length; j++) {
result[i][j] = Integer.parseInt(split[j]);
}
}
return result;
}

Finding non duplicate element in an array

I am stuck in the following program:
I have an input integer array which has only one non duplicate number, say {1,1,3,2,3}. The output should show the non duplicate element i.e. 2.
So far I did the following:
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j)
//System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
Restricting the solution in array is preferable. Avoid using collections,maps.
public class NonRepeatingElement {
public static void main(String[] args) {
int result =0;
int []arr={3,4,5,3,4,5,6};
for(int i:arr)
{
result ^=i;
}
System.out.println("Result is "+result);
}
}
Since this is almost certainly a learning exercise, and because you are very close to completing it right, here are the things that you need to change to make it work:
Move the declaration of flag inside the outer loop - the flag needs to be set to true every iteration of the outer loop, and it is not used anywhere outside the outer loop.
Check the flag when the inner loop completes - if the flag remains true, you have found a unique number; return it.
From Above here is the none duplicated example in Apple swift 2.0
func noneDuplicated(){
let arr = [1,4,3,7,3]
let size = arr.count
var temp = 0
for i in 0..<size{
var flag = true
temp = arr[i]
for j in 0..<size{
if(temp == arr[j]){
if(i != j){
flag = false
break
}
}
}
if(flag == true){
print(temp + " ,")
}
}
}
// output : 1 , 4 ,7
// this will print each none duplicated
/// for duplicate array
static void duplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =j+1;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
/*
for array of non duplicate elements in array just change int k=j+1; to int k = 0; in for loop
*/
static void NonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
for(int k =0 ;k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
}
count = 0;
}
}
public class DuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
duplicateItem(a);
NonDuplicateItem(a);
}
/// for first non repeating element in array ///
static void FirstNonDuplicateItem(int[] a){
/*
You can sort the array before you compare
*/
int temp =0;
for(int i=0; i<a.length;i++){
for(int j=0; j<a.length;j++){
if(a[i]<a[j]){
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
int count=0;
for(int j=0;j<a.length;j++) {
//int k;
for(int k =0; k<a.length;k++) {
if(a[j] == a[k]) {
count++;
}
}
if(count==1){
System.out.println(a[j]);
break;
}
count = 0;
}
}
public class NonDuplicateItem {
public static void main (String []args){
int[] a = {1,1,1,2,2,3,6,5,3,6,7,8};
FirstNonDuplicateItem(a);
}
I have a unique answer, it basically takes the current number that you have in the outer for loop for the array and times it by itself (basically the number to the power of 2). Then it goes through and every time it sees the number isn't equal to double itself test if its at the end of the array for the inner for loop, it is then a unique number, where as if it ever find a number equal to itself it then skips to the end of the inner for loop since we already know after one the number is not unique.
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int temp2 = 0;
int temp3 = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
temp2 = temp*temp;
for(int j=0;j<size;j++){
temp3 = temp*arr[j];
if(temp2==temp3 && i!=j)
j=arr.length
if(temp2 != temp3 && j==arr.length){
//System.out.println("Match found for "+temp);
flag = false;
result = temp;
break;
}
}
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
not tested but should work
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
boolean flag = true;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
temp = arr[i];
int count=0;
for(int j=0;j<size;j++){
if(temp == arr[j]){
count++;
}
}
if (count==1){
result=temp;
break;
}
}
return result;
}
Try:
public class Answer{
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
int[] b =new int[a.length];
//instead of a.length initialize it to maximum element value in a; to avoid
//ArrayIndexOutOfBoundsException
for(int i=0;i<a.length;i++){
int x=a[i];
b[x]++;
}
for(int i=0;i<b.length;i++){
if(b[i]==1){
System.out.println(i); // outputs 2
break;
}
}
}
}
PS: I'm really new to java i usually code in C.
Thanks #dasblinkenlight...followed your method
public class Solution {
public int singleNumber(int[] arr){
int size = arr.length;
int temp = 0;
int result = 0;
int[] arr1 = new int[size];
for(int i=0;i<size;i++){
boolean flag = true;
temp = arr[i];
for(int j=0;j<size;j++){
if(temp == arr[j]){
if(i != j){
// System.out.println("Match found for "+temp);
flag = false;
break;
}
}
}
if(flag == true)
result = temp;
}
return result;
}
public static void main(String[] args) {
int[] a = {1,1,3,2,3};
Solution sol = new Solution();
System.out.println("SINGLE NUMBER : "+sol.singleNumber(a));
}
}
One disastrous mistake was not enclosing the content of if(i != j) inside braces. Thanks all for your answers.
If you are coding for learning then you can solve it with still more efficiently.
Sort the given array using merge sort of Quick Sort.
Running time will be nlogn.
The idea is to use Binary Search.
Till required element found All elements have first occurrence at even index (0, 2, ..) and next occurrence at odd index (1, 3, …).
After the required element have first occurrence at odd index and next occurrence at even index.
Using above observation you can solve :
a) Find the middle index, say ‘mid’.
b) If ‘mid’ is even, then compare arr[mid] and arr[mid + 1]. If both are same, then the required element after ‘mid’ else before mid.
c) If ‘mid’ is odd, then compare arr[mid] and arr[mid – 1]. If both are same, then the required element after ‘mid’ else before mid.
Another simple way to do so..
public static void main(String[] art) {
int a[] = { 11, 2, 3, 1,1, 6, 2, 5, 8, 3, 2, 11, 8, 4, 6 ,5};
Arrays.sort(a);
System.out.println(Arrays.toString(a));
for (int j = 0; j < a.length; j++) {
if(j==0) {
if(a[j]!=a[j+1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(j==a.length-1) {
if(a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}else
if(a[j]!=a[j+1] && a[j]!=a[j-1]) {
System.out.println("The unique number is :"+a[j]);
}
}
}
Happy Coding..
Using multiple loops the time complexity is O(n^2), So the effective way to resolve this using HashMap which in the time complexity of O(n). Please find my answer below,
`public static int nonRepeatedNumber(int[] A) {
Map<Integer, Integer> countMap = new HashMap<>();
int result = -1;
for (int i : A) {
if (!countMap.containsKey(i)) {
countMap.put(i, 1);
} else {
countMap.put(i, countMap.get(i) + 1);
}
}
Optional<Entry<Integer, Integer>> optionalEntry = countMap.entrySet().stream()
.filter(e -> e.getValue() == 1).findFirst();
return optionalEntry.isPresent() ? optionalEntry.get().getKey() : -1;
}
}`

Sorting an array of strings in reverse alphabetical order in Java

I've been tasked with turning this code into a reverse sort, but for the life of me cannot figure out how to do it. These are my sort, findlargest and swap methods. I have a feeling I am missing something glaringly obvious here, any help would be really appreciated.
public static void sort(String[] arr)
{
for (int pass = 1; pass < arr.length; pass++)
{
int largestPos = findLargest(arr, arr.length - pass);
if (largestPos != arr.length - pass)
{
swap(arr, largestPos, arr.length - pass);
}
}
}
public static int findLargest(String[] arr, int num)
{
int largestPos = 0;
for (int i = 1; i <= num; i++)
{
if (arr[i].compareToIgnoreCase(arr[largestPos]) > 0)
{
largestPos = i;
}
}
return largestPos;
}
public static void swap(String[] arr, int first, int second)
{
String temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
}
Don't reinvent the wheel -
String[] strs = {"a", "b", "d", "c", "e"};
Arrays.sort(strs, Collections.reverseOrder(String.CASE_INSENSITIVE_ORDER));
System.out.println(Arrays.toString(strs));
[e, d, c, b, a]
Follow up from A. R. S.'s answer:
You could use a custom comparator if you are allowed to use the Arrays.Sort method...
Arrays.sort(stringArray, new Comparator<String>() {
#Override
public int compare(String t, String t1) {
return -t.compareToIgnoreCase(t1); //reverse the comparison, while ignoring case
}
});
Can you just turn findLargest to findSmallest, like this:
public static void sort(String[] arr) {
for (int pass = 1; pass < arr.length; pass++) {
int largestPos = findSmallest(arr, arr.length - pass);
if (largestPos != arr.length - pass) {
swap(arr, largestPos, arr.length - pass);
}
}
}
public static int findSmallest(String[] arr, int num) {
int largestPos = 0;
for (int i = 1; i <= num; i++) {
if (arr[i].compareToIgnoreCase(arr[largestPos]) < 0) {
largestPos = i;
}
}
return largestPos;
}
public static void swap(String[] arr, int first, int second) {
String temp = arr[first];
arr[first] = arr[second];
arr[second] = temp;
}
I think This is the one you need (if you don't think about collection framework).
public static void main(String args[]) {
String [] arr ={"abc","bac","cbc"};
String temp="";
for(int i=0;i<arr.length;i++){
for(int j=i+1;j<arr.length;j++){
if(arr[j].compareTo(arr[i]) > 0){
temp = arr[i] ;
arr[i] = arr[j];
arr[j] = temp;
}
}
}
for(String val:arr){
System.out.println(val);
}
}
Output is
cbc
bac
abc
you can use Arrays.sort(arr) to sort in alphabetical order.
and then reverse it.
public static void sort(String[] arr) {
Arrays.sort(arr);
for (int i=0; i<arr.length/2; i++) {
swap(arr,i,arr.length-1-i);
}
}
Try this one if you want. In your version you are moving the largest towards the end of the array, resulting in alphabetical order.
Just in case you insist on your original approach, I have made some minor changes to your code:
public static void sort(String[] arr)
{
for (int pass = 1; pass < arr.length; pass++)
{
int largestPos = findLargest(arr, pass-1);
if (largestPos != pass - 1)
{
swap(arr, largestPos, pass - 1);
}
}
}
public static int findLargest(String[] arr, int num)
{
int largestPos = num;
for (int i = num+1; i < arr.length; i++)
{
if (arr[i].compareToIgnoreCase(arr[largestPos]) > 0)
{
largestPos = i;
}
}
return largestPos;
}
The most trivial one though, as suggested by Ian Roberts, is simply Arrays.sort(arr, Collections.reverseOrder());.
So, first we need to create String array, then use Arrays.sort(String[]);, then use for to reverse sort array to reverse order.
import java.util.Arrays;
public class SortClass {
public static void main(String[] args) {
String[] arrayString = new String[5];
arrayString[0] = "Cat";
arrayString[1] = "Apple";
arrayString[2] = "Dog";
arrayString[3] = "Mouse";
arrayString[4] = "kitchen";
Arrays.sort(arrayString);
String[] arrReverse = new String[arrayString.length];
for (int i = arrayString.length - 1; i >= 0; i--) {
arrReverse[arrayString.length - 1 - i] = arrayString[i];
}
}
}
String arr[]= new String[];
String s; //input string
int count=0;
for(int i=0;i<=s.length()-k;i++){
arr[i]=s.substring(i,i+k); //using substring method
count++;
}
int i=0;
int b=count;
while(count>0){
int j=0;
while(j<b){
if((arr[i].compareTo(arr[j])>0)){
String temp= arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
j++;
}
i++;
count--;
}
for(i=0;i<b;i++)
System.out.println(arr[i]);

Categories

Resources