Sorting Arrays for int and string - java

How to sort an int[] array, do i have to use this or can i just use the in built methods by java?
for (int x = 0; x < days.length - 1; w++) {
for (short i = 0; i < days.length - 1; i++) {
if (days[i].(days[i + 1]) > 0) {
days = days[i];
days[i] = days[i + 1];
days[i + 1] = days;
}
}
}

I wrote a snippet to sort a simple string array. Reproduced below:
int length = winners.length;
for(int i=0; i<length-1; i++){
for(int j=0; j<length-i-1; j++){
if(winners[j].compareTo(winners[j+1]) > 0){
//Swap the elements
String temp = winners[j];
winners[j] = winners[j+1];
winners[j+1] = temp;
}
}
}
for(String winner: winners){
System.out.println(winner);
}
This is working correctly.
If you want to ignore case you can use compareToIgnoreCase method.

The simplest way to sort arrays is with Arrays.sort:
String[] array = {"c", "a", "b"};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
output -> [a, b, c]
String[] array = {"2", "1", "3"};
Arrays.sort(array);
System.out.println(Arrays.toString(array));
output -> [1, 2, 3]
The same process will work for an array of ints (or any primitive) too

Related

How can I create an Array in Descending Order?

I'm working on this project using Arrays. I have a method called createRandomIntArray that creates an array. This method is meant to return the Array in descending order. I have been able to do just that but I want to know if there is a more effective way to write this method than the way I wrote it. I have my code below.
public static int[] createRandomIntArray(int n) {
Random random = new Random();
int[] result = new int[n];
for (int i = 0; i < n; i++) {
result[i] = random.nextInt(n);
}
Arrays.sort(result);
for (int i = 0; i < result.length / 2; i++) {
int temp = result[i];
result[i] = result[result.length - i - 1];
result[result.length - i - 1] = temp;
}
return result;
}
You could avoid reversing the sorted array by directly sorting reverse order:
Arrays.sort(result, Comparator.reverseOrder());
As mentioned in the comments one could use Random.ints(…) if you’re not tied to using arrays:
random.ints(n, 0, n).boxed().sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Using Java Streams
private static int[] createRandomIntArray(int n) {
return ThreadLocalRandom.current().ints() // Stream of random ints
.limit(n) // Limit the stream to n values
.boxed() // Convert to Stream of Integer Objects for reverse sorting
.sorted(Collections.reverseOrder()) // Sort in reverse Order
.mapToInt(Integer::intValue) // Map back to primitive ints
.toArray(); // as Array
}
public class SortDes {
public static void main(String[] args) {
int [] arr = new int [] {5, 2, 8, 7, 1};
int temp = 0;
System.out.println("Elements of original array: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
for (int i = 0; i < arr.length; i++) {
for (int j = i+1; j < arr.length; j++) {
if(arr[i] < arr[j]) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
}
System.out.println();
System.out.println("Elements of array sorted in descending order: ");
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i] + " ");
}
}
}
There's an alternative which is using Stream.
Arrays.stream(result).sorted(Comparator.reverseOrder());

Keeping indexes of an elements in the array after sorting in Java

I want that sorting array without actually changing its data. So I want only keep its indexes in another array. For this I use Bubble Sort algorithm, and at every swapping step I change elements of new array which keeps indexes of actual array. That's my code, but it doesn't work correctly
int[] bSort(int[] arrivalTimes) {
int[] sequence = new int[arrivalTimes.length];
for (int i = 0; i < sequence.length; i++) {
sequence[i] = i;
}
for (int i = 0; i < arrivalTimes.length - 1; i++) {
for (int j = i + 1; j < arrivalTimes.length; j++) {
if (arrivalTimes[i] > arrivalTimes[j]) {
int temp = sequence[i];
sequence[i] = sequence[j];
sequence[j] = temp;
}
}
}
return sequence;
}
So if input array is [2, 5, 1, 0, 4]
Then sequence array should be [3, 2, 0, 4, 1] (indexes of actual array)
You're forgetting to sort the actual array also. If the arrivalTimes array isn't sorted, your condition will not act the way you expect.
int[] bSort(int[] arrivalTimes) {
int[] sequence = new int[arrivalTimes.length];
for (int i = 0; i < sequence.length; i++) {
sequence[i] = i;
}
for (int i = 0; i < arrivalTimes.length - 1; i++) {
for (int j = i + 1; j < arrivalTimes.length; j++) {
if (arrivalTimes[i] > arrivalTimes[j]) {
int temp = sequence[i];
sequence[i] = sequence[j];
sequence[j] = temp;
int temp2 = arrivalTimes[i];
arrivalTimes[i] = arrivalTimes[j];
arrivalTimes[j] = temp2;
}
}
}
return sequence;
}
This is an inefficient solution though. I suspect this is part of some algorithms assignment so I'll leave the optimisations up to you.

Shuffle an array of strings so that the sting must be completely shuffled and not in its original index in Java

Original Array
Array[]={"Car","Truck","Boat"};
Shuffled Array
Array[]={"Truck","Boat","Car"};
Dont want it Semi-Shuffled
like
Array[]={"Truck","Car","Boat"};
where Car and Truck are swapped but not Boat.
I read this is called Derangement of an array but I cant find one that helps with Strings.
Here's one solution to generate derangement of an array the with O(n) time and O(1) space complexity.
String[] strArray = { "Truck", "Car", "Boat" };
String temp = strArray[0];
for (int i = 0; i < strArray.length - 1; i++) {
strArray[i] = strArray[i + 1];
}
strArray[strArray.length - 1] = temp;
Arrays.stream(strArray).forEach((e) -> System.out.print(e + " "));
I just shifted every element to its left.
And here's the output:
Car Boat Truck
String[] arr = { "Car", "Truck", "Boat" };
Arrays.sort(arr);
for (int i = 0; i <= arr.length - 1; i++) {
System.out.println(arr[i]);
}

Sort an array such a way that First half should be in ascending order Second half should be in descending order in java

I have searched a lot in google but I didnt get any kind of solution I could use. Suppose input of array is:
{3,1,2,4,9,8,7,6,5,10}
then output must be like this:
{1,2,3,4,5,10,9,8,7,6}
by using Basic Java .
Your array: {3,1,2,4,9,8,7,6,5,10}
Sort it in ascending order: {1,2,3,4,5,6,7,8,9,10}
Break this array into two half arrays: {1,2,3,4,5}{6,7,8,9,10}
Sort the second array in descending order or reverse it: {10, 9,8,7,6}
Add the second array to the first array & you get: {1,2,3,4,5,10,9,8,7,6}
This would be the minimal code which uses an array of primitive ints:
static final int[] xs = {3,1,2,4,9,8,7,6,5,10};
static void sortAndReverse() {
Arrays.sort(xs);
for (int i = xs.length/2; i < dest(i); i++) {
int tmp = xs[i]; xs[i] = xs[dest(i)]; xs[dest(i)] = tmp;
}
System.out.println(Arrays.toString(xs));
}
static int dest(int i) { return 3*xs.length/2-i-1; }
If you're not ashamed of using wrapper objects, then this is unbeatable:
final Integer[] xs = {3,1,2,4,9,8,7,6,5,10};
final List<Integer> list = Arrays.asList(xs);
Collections.sort(list);
Collections.reverse(list.subList(list.size()/2, list.size()));
System.out.println(Arrays.toString(xs));
Please find the below code
import java.util.Arrays;
public class fre {
public static void main(String[] args) {
int[] vals = { 3, 1, 2, 4, 9, 8, 7, 6, 5, 10 };
Arrays.sort(vals); // Sorts the basic first array
int[] vals2 = Arrays.copyOfRange(vals, vals.length / 2, vals.length); // Gets the las values of the arrays i.e. it devies the array in multiple same part and another array is created
// Below loop will reverse the second array
for (int i = 0; i < vals2.length / 2; i++) {
int temp = vals2[i];
vals2[i] = vals2[vals2.length - 1 - i];
vals2[vals2.length - 1 - i] = temp;
}
vals = Arrays.copyOfRange(vals, 0, vals.length / 2);
// Final array array1and2 will be created where we will append first array with second array
int[] array1and2 = new int[vals.length + vals2.length];
System.arraycopy(vals, 0, array1and2, 0, vals.length);
System.arraycopy(vals2, 0, array1and2, vals.length, vals2.length);
// Prints the final result array
System.out.println(Arrays.toString(array1and2));
}
}
Output
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
You can use the java features to do this too ... Use
public static <T> void sort(T[] a,
int fromIndex,
int toIndex,
Comparator<? super T> c)
But the elements need to be objects ... The comparator needs to be changed while sorting the first half and second half of the array.
Should be a bit simpler than manually reversing each item in the second half.
Integer [] array = { 3,1,2,4,9,8,7,6,5,10 };
Arrays.sort(array);
Arrays.sort(array, array.length/2, array.length, new Comparator<Integer>(){
#Override
public int compare(Integer o1, Integer o2)
{
return -o1.compareTo(o2);
}
});
System.out.println(Arrays.toString(array));
[1, 2, 3, 4, 5, 10, 9, 8, 7, 6]
IPSOS isn't it?
int m;
if(array.length%2==0)
m=array.length/2;
else
m=(array.length+1)/2;
for(int i=0; i<array.length; ++i){
if(i<m){
int min = i;
for(int j=i+1; j<m;++j){
if(array[min]>array[j]){
min=j;
}
int tem = array[i];
array[i]=array[min];
array[min]=tem;
}
}
else {
int max = i;
for(int k=i+1; k<array.length; ++k){
if(array[max]<array[k]){
max=k;
}
int te = array[i];
array[i]=array[max];
array[max]=te;
}
}
}
for(int i=0;i<array.length;++i){
System.out.print(array[i] + " ");
}
1. Sort the array input_Array[]
2. j = lenght(input_Array)-1
3. loop i = lenght(input_Array)/2 to j
swap(input_Array[i] , input_Array[j-i])
input: 3,1,2,4,9,8,7,6,5,10
output: 1 3 5 7 9 10 8 6 4 2 (uniform acceding and descending )
public class AscendingDecending {
public static void main(String[]args) {
int a[]= {2,3,2,5,7,5,6,3};
int i,j,temp;
//Traverse the element of array
System.out.println("Input:");
for(i=0; i<a.length; i++) {
System.out.print(" "+ a[i]);
}
//lets move for ascending function
System.out.println("");
System.out.println("Output:");
//Create a Swap Function for sorting
for(i=0; i<a.length; i++) {
for(j=i+1; j<a.length; j++) {
if(a[i]>a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
//For Descending
for(i=0; i<a.length; i++) {
for(int j=i+1; j<a.length; j++) {
if(a[i]<a[j]) {
temp= a[i];
a[i]= a[j];
a[j]= temp;
}
}
}
// Now the input is in sorted order
System.out.println(" ");
for(i=0; i<a.length/2; i++) {
System.out.print(" "+ a[i]);
}
}
}
I hope this piece of code will help:
static void printarray(int[] arr, int len)
{
Arrays.sort(arr);
for (int i = 0; i < len / 2; i++)
System.out.println(arr[i]);
for (int j = len - 1; j >= len / 2; j--)
System.out.println(arr[j]);
}

mergeTwo CodingBat puzzle in Java

I am trying to solve this CodingBat problem:
Start with two arrays of strings, A and B, each with its elements in alphabetical order and without duplicates. Return a new array containing the first N elements from the two arrays. The result array should be in alphabetical order and without duplicates. A and B will both have a length which is N or more. The best "linear" solution makes a single pass over A and B, taking advantage of the fact that they are in alphabetical order, copying elements directly to the new array.
mergeTwo({"a", "c", "z"}, {"b", "f", "z"}, 3) → {"a", "b", "c"}
mergeTwo({"a", "c", "z"}, {"c", "f", "z"}, 3) → {"a", "c", "f"}
mergeTwo({"f", "g", "z"}, {"c", "f", "g"}, 3) → {"c", "f", "g"}
Attempt:
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] op = new String[a.length + b.length];
for (int i = 0; i < a.length; i++) {
op[i] = a[i];
}
int j = 0;
for (int i = 0; i < op.length; i++) {
if (op[i] == null) {
j = i;
break;
}
}
for (int i = 0; i < b.length; i++) {
op[j] = b[i];
j++;
}
Arrays.sort(op);
ArrayList<String> help = new ArrayList<String>();
for (int i = 0; i < op.length - 1; i++) {
if (op[i] != op[i + 1]) {
help.add(op[i]);
}
}
String[] res = new String[help.size()];
for (int i = 0; i < help.size(); i++) {
res[i] = help.get(i);
}
String[] op2 = new String[n];
for (int i = 0; i < n; i++) {
op2[i] = res[i];
}
return op2;
}
So the problem is that all the tests pass except one:
Why is that?
This is the line that has the problem:
if (op[i] != op[i + 1]) {
You are looking for a pattern where the lsst of several identical strings doesn't match the next string.
In the failing case, there is no "next string" because there are exactly 3 unique strings.
One way to deal with that is to look for a pattern where this string is different than the last string but you don't really check the array for the last string (since the 1st array element has no last string). You use a variable, say last, to store the last string and transfer only when this element isn't equal to last.
Try this ...
String last = "";
for (int i = 0; i < op.length - 1; i++) {
if (!op[i].equals(last)) {
help.add(op[i]);
}
last = op[i];
}
Also note that in Java strings are compared with the equals() method.
With Java8 it can be done with few simple rows of code:
public String[] mergeTwo(String[] a, String[] b, int n)
{
Set<String> set = new HashSet();
set.addAll(Arrays.asList(a));
set.addAll(Arrays.asList(b));
List<String> list = new ArrayList(set);
return list.subList(0, n).toArray(new String[n]);
}
Another solution:
public String[] mergeTwo(String[] a, String[] b, int n) {
String[] arr = new String[n];
int aI = 0;
int bI = 0;
for(int i = 0; i < n; i++) {
if(a[aI].compareTo(b[bI]) < 0) {
arr[i] = a[aI];
aI++;
} else if(a[aI].compareTo(b[bI]) > 0) {
arr[i] = b[bI];
bI++;
} else {
arr[i] = a[aI];
aI++;
bI++;
}
}
return arr;
}

Categories

Resources