These numbers are stored in the same integer variable. How would I go about sorting the integers in order lowest to highest?
11367
11358
11421
11530
11491
11218
11789
There are two options, really:
Use standard collections, as explained by Shakedown
Use Arrays.sort
E.g.,
int[] ints = {11367, 11358, 11421, 11530, 11491, 11218, 11789};
Arrays.sort(ints);
System.out.println(Arrays.asList(ints));
That of course assumes that you already have your integers as an array.
If you need to parse those first, look for String.split and Integer.parseInt.
You can put them into a list and then sort them using their natural ordering, like so:
final List<Integer> list = Arrays.asList(11367, 11358, 11421, 11530, 11491, 11218, 11789);
Collections.sort( list );
// Use the sorted list
If the numbers are stored in the same variable, then you'll have to somehow put them into a List and then call sort, like so:
final List<Integer> list = new ArrayList<Integer>();
list.add( myVariable );
// Change myVariable to another number...
list.add( myVariable );
// etc...
Collections.sort( list );
// Use the sorted list
Collections.sort( List )
Well, if you want to do it using an algorithm. There are a plethora of sorting algorithms out there. If you aren't concerned too much about efficiency and more about readability and understandability. I recommend Insertion Sort. Here is the psudo code, it is trivial to translate this into java.
begin
for i := 1 to length(A)-1 do
begin
value := A[i];
j := i - 1;
done := false;
repeat
{ To sort in descending order simply reverse
the operator i.e. A[j] < value }
if A[j] > value then
begin
A[j + 1] := A[j];
j := j - 1;
if j < 0 then
done := true;
end
else
done := true;
until done;
A[j + 1] := value;
end;
end;
For sorting narrow range of integers try Counting sort, which has a complexity of O(range + n), where n is number of items to be sorted. If you'd like to sort something not discrete use optimal n*log(n) algorithms (quicksort, heapsort, mergesort). Merge sort is also used in a method already mentioned by other responses Arrays.sort. There is no simple way how to recommend some algorithm or function call, because there are dozens of special cases, where you would use some sort, but not the other.
So please specify the exact purpose of your application (to learn something (well - start with the insertion sort or bubble sort), effectivity for integers (use counting sort), effectivity and reusability for structures (use n*log(n) algorithms), or zou just want it to be somehow sorted - use Arrays.sort :-)). If you'd like to sort string representations of integers, than u might be interrested in radix sort....
import java.util.Arrays;
public class sortNumber {
public static void main(String[] args) {
// Our array contains 13 elements
int[] array = {9, 238, 248, 138, 118, 45, 180, 212, 103, 230, 104, 41, 49};
Arrays.sort(array);
System.out.printf(" The result : %s", Arrays.toString(array));
}
}
if array.sort doesn't have what your looking for you can try this:
package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
ArrayList<AffineTransform> affs;
ListIterator<AffineTransform> li;
Integer count, count2;
/**
* #param args
*/
public static void main(String[] args) {
new QuicksortAlgorithm();
}
public QuicksortAlgorithm(){
count = new Integer(0);
count2 = new Integer(1);
affs = new ArrayList<AffineTransform>();
for (int i = 0; i <= 128; i++){
affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
}
affs = arrangeNumbers(affs);
printNumbers();
}
public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
while (list.size() > 1 && count != list.size() - 1){
if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
list.add(count, list.get(count2));
list.remove(count2 + 1);
}
if (count2 == list.size() - 1){
count++;
count2 = count + 1;
}
else{
count2++;
}
}
return list;
}
public void printNumbers(){
li = affs.listIterator();
while (li.hasNext()){
System.out.println(li.next());
}
}
}
Take Inputs from User and Insertion Sort. Here is how it works:
package com.learning.constructor;
import java.util.Scanner;
public class InsertionSortArray {
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
System.out.println("enter number of elements");
int n=s.nextInt();
int arr[]=new int[n];
System.out.println("enter elements");
for(int i=0;i<n;i++){//for reading array
arr[i]=s.nextInt();
}
System.out.print("Your Array Is: ");
//for(int i: arr){ //for printing array
for (int i = 0; i < arr.length; i++){
System.out.print(arr[i] + ",");
}
System.out.println("\n");
int[] input = arr;
insertionSort(input);
}
private static void printNumbers(int[] input) {
for (int i = 0; i < input.length; i++) {
System.out.print(input[i] + ", ");
}
System.out.println("\n");
}
public static void insertionSort(int array[]) {
int n = array.length;
for (int j = 1; j < n; j++) {
int key = array[j];
int i = j-1;
while ( (i > -1) && ( array [i] > key ) ) {
array [i+1] = array [i];
i--;
}
array[i+1] = key;
printNumbers(array);
}
}
}
Related
Write a function:
class Solution{
public int solution(int[] A);
}
that, given an array A of N integers, returns the smallest positive integer(greater than 0)
that does not occur in A.
For example, given A = [1,3,6,4,1,2], the function should return 5.
Given A = [1,2,3], the function should return 4.
Given A = [-1, -3], the function should return 1.
Write an efficient algorithm for the following assumptions.
N is an integer within the range [1..100,000];
each element of array A is an integer within the range [-1,000,000..1,000,000].
I wrote the following algorithm in Java:
public class TestCodility {
public static void main(String args[]){
int a[] = {1,3,6,4,1,2};
//int a[] = {1,2,3};
//int b[] = {-1,-3};
int element = 0;
//checks if the array "a" was traversed until the last position
int countArrayLenght = 0;
loopExtern:
for(int i = 0; i < 1_000_000; i++){
element = i + 1;
countArrayLenght = 0;
loopIntern:
for(int j = 0; j < a.length; j++){
if(element == a[j]){
break loopIntern;
}
countArrayLenght++;
}
if(countArrayLenght == a.length && element > 0){
System.out.println("Smallest possible " + element);
break loopExtern;
}
}
}
}
It does the job but I am pretty sure that it is not efficient. So my question is, how to improve this algorithm so that it becomes efficient?
You should get a grasp on Big O, and runtime complexities.
Its a universal construct for better understanding the implementation of efficiency in code.
Check this website out, it shows the graph for runtime complexities in terms of Big O which can aid you in your search for more efficient programming.
http://bigocheatsheet.com/
However, long story short...
The least amount of operations and memory consumed by an arbitrary program is the most efficient way to achieve something you set out to do with your code.
You can make something more efficient by reducing redundancy in your algorithms and getting rid of any operation that does not need to occur to achieve what you are trying to do
Point is to sort your array and then iterate over it. With sorted array you can simply skip all negative numbers and then find minimal posible element that you need.
Here more general solution for your task:
import java.util.Arrays;
public class Main {
public static int solution(int[] A) {
int result = 1;
Arrays.sort(A);
for(int a: A) {
if(a > 0) {
if(result == a) {
result++;
} else if (result < a){
return result;
}
}
}
return result;
}
public static void main(String args[]){
int a[] = {1,3,6,4,1,2};
int b[] = {1,2,3};
int c[] = {-1,-3};
System.out.println("a) Smallest possible " + solution(a)); //prints 5
System.out.println("b) Smallest possible " + solution(b)); //prints 4
System.out.println("c) Smallest possible " + solution(c)); //prints 1
}
}
Complexity of that algorithm should be O(n*log(n))
The main idea is the same as Denis.
First sort, then process but using java8 feature.
There are few methods that may increase timings.(not very sure how efficient java 8 process them:filter,distinct and even take-while ... in the worst case you have here something similar with 3 full loops. One additional loop is for transforming array into stream). Overall you should get the same run-time complexity.
One advantage could be on verbosity, but also need some additional knowledge compared with Denis solution.
import java.util.function.Supplier;
import java.util.stream.IntStream;
public class AMin
{
public static void main(String args[])
{
int a[] = {-2,-3,1,2,3,-7,5,6};
int[] i = {1} ;
// get next integer starting from 1
Supplier<Integer> supplier = () -> i[0]++;
//1. transform array into specialized int-stream
//2. keep only positive numbers : filter
//3. keep no duplicates : distinct
//4. sort by natural order (ascending)
//5. get the maximum stream based on criteria(predicate) : longest consecutive numbers starting from 1
//6. get the number of elements from the longest "sub-stream" : count
long count = IntStream.of(a).filter(t->t>0).distinct().sorted().takeWhile(t->t== supplier.get()).count();
count = (count==0) ? 1 : ++count;
//print 4
System.out.println(count);
}
}
There are many solutions with O(n) space complexity and O(n) type complexity. You can convert array to;
set: array to set and for loop (1...N) check contains number or not. If not return number.
hashmap: array to map and for loop (1...N) check contains number or not. If not return number.
count array: convert given array to positive array count array like if arr[i] == 5, countArr[5]++, if arr[i] == 1, countArr[1]++ then check each item in countArr with for loop (1...N) whether greate than 1 or not. If not return it.
For now, looking more effective algoritm like #Ricola mentioned. Java solution with O(n) time complexity and O(1) space complexity:
static void swap(final int arr[], final int i,final int j){
final int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static boolean isIndexInSafeArea(final int arr[], final int i){
return arr[i] > 0 && arr[i] - 1 < arr.length && arr[i] != i + 1 ;
}
static int solution(final int arr[]){
for (int i = 0; i < arr.length; i++) {
while (isIndexInSafeArea(arr,i) && arr[i] != arr[arr[i] - 1]) {
swap(arr, i, arr[i] - 1);
}
}
for (int i = 0; i < arr.length; i++) {
if (arr[i] != i + 1) {
return i+1;
}
}
return arr.length + 1;
}
I just had an online coding interview and one of the questions asked there is for a given array of integers, find out the number of pairs whose summation is equal to a certain number (passed as parameter inside the method ). For example an array is given as,
int[] a = {3, 2, 1, 45, 27, 6, 78, 9, 0};
int k = 9; // given number
So, there will be 2 pairs (3, 6) and (9, 0) whose sum is equal to 9. It's good to mention that how the pairs are formed doesn't matter. The means (3,6) and (6,3) will be considered as same pair. I provided the following solution (in Java) and curious to know if I missed any edge cases?
public static int numberOfPairs(int[] a, int k ){
int len = a.length;
if (len == 0){
return -1;
}
Arrays.sort(a);
int count = 0, left = 0, right = len -1;
while( left < right ){
if ( a[left] + a[right] == k ){
count++;
if (a[left] == a[left+1] && left < len-1 ){
left++;
}
if ( a[right] == a[right-1] && right >1 ){
right-- ;
}
right--; // right-- or left++, otherwise, will get struck in the while loop
}
else if ( a[left] + a[right] < k ){
left++;
}
else {
right--;
}
}
return count;
}
Besides, can anyone propose any alternative solution of the problem ? Thanks.
Following solution will return the number of unique pairs
public static int numberOfPairs(Integer[] array, int sum) {
Set<Integer> set = new HashSet<>(Arrays.asList(array));
// this set will keep track of the unique pairs.
Set<String> uniquePairs = new HashSet<String>();
for (int i : array) {
int x = sum - i;
if (set.contains(x)) {
int[] y = new int[] { x, i };
Arrays.sort(y);
uniquePairs.add(Arrays.toString(y));
}
}
//System.out.println(uniquePairs.size());
return uniquePairs.size();
}
The time complexity will be O(n).
Hope this helps.
You can use the HashMap<K,V> where K: a[i] and V: k-a[i]
This may result in an incorrect answer if there are duplicates in an array.
Say for instances:
int a[] = {4, 4, 4, 4, 4, 4, 4, 4, 4}
where k = 8 or:
int a[] = {1, 3, 3, 3, 3, 1, 2, 1, 2}
where k = 4.
So in order to avoid that, we can have a List<List<Integer>> , which can check each pair and see if it is already in the list.
static int numberOfPairs(int[] a, int k)
{
List<List<Integer>> res = new ArrayList<>();
Map<Integer, Integer> map = new HashMap<>();
for(int element:a)
{
List<Integer> list = new ArrayList<>();
if(map.containsKey(element))
{
list.add(element);
list.add(map.get(element));
if(!res.contains(list))
res.add(list);
}
else
map.put(k - element, element);
}
return res.size();
}
Your solution is overly complex, you can do this exercise in a much easier manner:
public static int numberOfPairs(int[] a, int k ){
int count=0;
List<Integer> dedup = new ArrayList<>(new HashSet<>(Arrays.asList(a)));
for (int x=0 ; x < dedup.size() ; x++ ){
for (int y=x+1 ; y < dedup.size() ; y++ ){
if (dedup.get(x)+dedup.get(y) == k)
count++;
}
}
return count;
}
The trick here is to have a loop starting after the first loop's index to not count the same values twice, and not compare it with your own index. Also, you can deduplicate the array to avoid duplicate pairs, since they don't matter.
You can also sort the list, then break the loop as soon as your sum goes above k, but that's optimization.
This code will give you count of the pairs that equals to given sum and as well as the pair of elements that equals to sum
private void pairofArrayElementsEqualstoGivenSum(int sum,Integer[] arr){
int count=0;
List numList = Arrays.asList(arr);
for (int i = 0; i < arr.length; i++) {
int num = sum - arr[i];
if (numList.contains(num)) {
count++;
System.out.println("" + arr[i] + " " + num + " = "+sum);
}
}
System.out.println("Total count of pairs "+count);
}
Given an array of integers and a target value, determine the number of pairs of array elements with a difference equal to a target value.
The function has the following parameters:
k: an integer, the target difference
arr: an array of integers
Using LINQ this is nice solution:
public static int CountNumberOfPairsWithDiff(int k, int[] arr)
{
var numbers = arr.Select((value) => new { value });
var pairs = from num1 in numbers
join num2 in numbers
on num1.value - k equals num2.value
select new[]
{
num1.value, // first number in the pair
num2.value, // second number in the pair
};
foreach (var pair in pairs)
{
Console.WriteLine("Pair found: " + pair[0] + ", " + pair[1]);
}
return pairs.Count();
}
I'm learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:
class example
{
public static void main(String args[])
{
String a[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
int b[] = new int[] {1, 2, 3, 4, 5};
for(int n=0;n<5;n++)
{
System.out.print (a[n] + "...");
System.out.println (b[n]);
}
System.out.println (" ");
java.util.Arrays.sort(a);
for(int n=0;n<5;n++)
{
System.out.print (a[n] + "...");
System.out.println (b[n]);
}
}
In a nutshell, this class created two arrays with five spaces each. It fills one with names of characters from the West Wing, and fills the other with numbering from one to five. We can say that the data in these two strings corresponds to each other.
Now, the program sorts the array with the names in it using Arrays.sort(). After printing the array again, you can see that while the names are now in alphabetical order, the numbers do not correspond anymore as the second array is unchanged.
How can I shuffle the contents of the second array to match the sort requirements of the first? The solution must also be flexible to allow for changes in the scope and size of the program. Please do not post any answers asking me to change my methodology with the arrays, or propose a more 'efficient' way of doing things. This is for educational purposed and I'd like a straight solution to the example code provided. Thanks in advance!
EDIT: I do NOT want to create an additional class, however I think some form of sorting through nested loops might be an option instead of Arrays.sort().
Below is the code without using any Map Collection, but if you want to use Map then it becomes very easy. Add both the arrays into map and sort it.
public static void main(String args[]) {
String a[] = new String[] {
"Sam", "Claudia", "Josh", "Toby", "Donna"
};
int b[] = new int[] {
1, 2, 3, 4, 5
};
for (int n = 0; n < 5; n++) {
System.out.print(a[n] + "...");
System.out.println(b[n]);
}
System.out.println(" ");
//java.util.Arrays.sort(a);
/* Bubble Sort */
for (int n = 0; n < 5; n++) {
for (int m = 0; m < 4 - n; m++) {
if ((a[m].compareTo(a[m + 1])) > 0) {
String swapString = a[m];
a[m] = a[m + 1];
a[m + 1] = swapString;
int swapInt = b[m];
b[m] = b[m + 1];
b[m + 1] = swapInt;
}
}
}
for (int n = 0; n < 5; n++) {
System.out.print(a[n] + "...");
System.out.println(b[n]);
}
}
Some people propose making a product type. That is feasible only if the amount of elements is small. By introducing another object you add object overhead (30+ bytes) for each element and a performance penalty of a pointer (also worsening cache locality).
Solution without object overhead
Make a third array. Fill it with indices from 0 to size-1. Sort this array with comparator function polling into the array according to which you want to sort.
Finally, reorder the elements in both arrays according to indices.
Alternative solution
Write the sorting algorithm yourself. This is not ideal, because you might make a mistake and the sorting efficiency might be subpar.
You have to ZIP your two arrays into an array which elements are instances of a class like:
class NameNumber
{
public NameNumber(String name, int n) {
this.name = name;
this.number = n;
}
public String name;
public int number;
}
And sort that array with a custom comparator.
Your code should be something like:
NameNumber [] zip = new NameNumber[Math.min(a.length,b.length)];
for(int i = 0; i < zip.length; i++)
{
zip[i] = new NameNumber(a[i],b[i]);
}
Arrays.sort(zip, new Comparator<NameNumber>() {
#Override
public int compare(NameNumber o1, NameNumber o2) {
return Integer.compare(o1.number, o2.number);
}
});
You should not have two parallel arrays. Instead, you should have a single array of WestWingCharacter objects, where each object would have a field name and a field number.
Sorting this array by number of by name would then be a piece of cake:
Collections.sort(characters, new Comparator<WestWingCharacter>() {
#Override
public int compare(WestWingCharacter c1, WestWingCharacter c2) {
return c1.getName().compareTo(c2.getName();
}
});
or, with Java 8:
Collections.sort(characters, Comparator.comparing(WestWingCharacter::getName));
Java is an OO language, and you should thus use objects.
What you want is not possible because you don't know internally how Arrays.sort swap the elements in your String array, so there is no way to swap accordingly the elements in the int array.
You should create a class that contains the String name and the int position as parameter and then sort this class only with the name, providing a custom comparator to Arrays.sort.
If you want to keep your current code (with 2 arrays, but this not the ideal solution), don't use Arrays.sort and implement your own sorting algorithm. When you swap two names, get the index of them and swap the two integers in the other array accordingly.
Here is the answer for your query.
public class Main {
public static void main(String args[]){
String name[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
int id[] = new int[] {1, 2, 3, 4, 5};
for ( int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int dtmp=0;
String stmp=null;
if (id[i] > id[j]) {
dtmp = rate[i];
id[i] = id[j];
id[j] = dtmp;
stmp = name[i];
name[i]=name[j];
name[j]=stmp;
}
}
}
System.out.println("Details are :");
for(int i=0;i<n;i++){
System.out.println(name[i]+" - "+id[i]);
}
}
}
The same solution, as a function that can be added to some utils class:
public static final boolean INCREASING = true;
public static final boolean DECREASING = false;
#SuppressWarnings("unchecked")
public static <T extends Comparable, U extends Object> void bubbleSort(ArrayList<T> list1, ArrayList<U>list2, boolean order) {
int cmpResult = (order ? 1 : -1);
for (int i = 0; i < list1.size() - 1; i++) {
for (int j = 0; j <= i; j++) {
if (list1.get(j).compareTo(list1.get(j+1)) == cmpResult) {
T tempComparable = list1.get(j);
list1.set(j , list1.get(j + 1));
list1.set(j + 1 , tempComparable);
U tempObject = list2.get(j);
list2.set(j , list2.get(j + 1));
list2.set(j + 1 , tempObject);
}
}
}
}
The arrays are not linked in any way. Like someone pointed out take a look at
SortedMap http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html
TreeMap http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
import java.util.*;
class mergeArrays2
{
public static void main(String args[])
{
String a1[]={"Sam", "Claudia", "Josh", "Toby", "Donna"};
Integer a2[]={11, 2, 31, 24, 5};
ArrayList ar1=new ArrayList(Arrays.asList(a1));
Collections.sort(ar1);
ArrayList ar2=new ArrayList(Arrays.asList(a2));
Collections.sort(ar2);
System.out.println("array list"+ar1+ " "+ar2);
}
}
I'm trying to make a program that consists of an array of 10 integers which all has a random value, so far so good.
However, now I need to sort them in order from lowest to highest value and then print it onto the screen, how would I go about doing so?
(Sorry for having so much code for a program that small, I ain't that good with loops, just started working with Java)
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
Loops are also very useful to learn about, esp When using arrays,
int[] array = new int[10];
Random rand = new Random();
for (int i = 0; i < array.length; i++)
array[i] = rand.nextInt(100) + 1;
Arrays.sort(array);
System.out.println(Arrays.toString(array));
// in reverse order
for (int i = array.length - 1; i >= 0; i--)
System.out.print(array[i] + " ");
System.out.println();
Add the Line before println and your array gets sorted
Arrays.sort( array );
It may help you understand loops by implementing yourself. See Bubble sort is easy to understand:
public void bubbleSort(int[] array) {
boolean swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < array.length - j; i++) {
if (array[i] > array[i + 1]) {
tmp = array[i];
array[i] = array[i + 1];
array[i + 1] = tmp;
swapped = true;
}
}
}
}
Of course, you should not use it in production as there are better performing algorithms for large lists such as QuickSort or MergeSort which are implemented by Arrays.sort(array)
Take a look at Arrays.sort()
I was lazy and added the loops
import java.util.Arrays;
public class Sort {
public static void main(String args[])
{
int [] array = new int[10];
for ( int i = 0 ; i < array.length ; i++ ) {
array[i] = ((int)(Math.random()*100+1));
}
Arrays.sort( array );
for ( int i = 0 ; i < array.length ; i++ ) {
System.out.println(array[i]);
}
}
}
Your array has a length of 10. You need one variable (i) which takes the values from 0to 9.
for ( int i = 0 ; i < array.length ; i++ )
^ ^ ^
| | ------ increment ( i = i + 1 )
| |
| +-------------------------- repeat as long i < 10
+------------------------------------------ start value of i
Arrays.sort( array );
Is a library methods that sorts arrays.
Arrays.sort(yourArray)
will do the job perfectly
For natural order : Arrays.sort(array)
For reverse Order : Arrays.sort(array, Collections.reverseOrder()); -- > It is a static method in Collections class which will further call an inner class of itself to return a reverse Comparator.
You can sort a int array with Arrays.sort( array ).
See below, it will give you sorted ascending and descending both
import java.util.Arrays;
import java.util.Collections;
public class SortTestArray {
/**
* Example method for sorting an Integer array
* in reverse & normal order.
*/
public void sortIntArrayReverseOrder() {
Integer[] arrayToSort = new Integer[] {
new Integer(48),
new Integer(5),
new Integer(89),
new Integer(80),
new Integer(81),
new Integer(23),
new Integer(45),
new Integer(16),
new Integer(2)
};
System.out.print("General Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort);
System.out.print("\n\nAscending Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
Arrays.sort(arrayToSort, Collections.reverseOrder());
System.out.print("\n\nDescinding Order is : ");
for (Integer i : arrayToSort) {
System.out.print(i.intValue() + " ");
}
}
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
SortTestArray SortTestArray = new SortTestArray();
SortTestArray.sortIntArrayReverseOrder();
}}
Output will be
General Order is : 48 5 89 80 81 23 45 16 2
Ascending Order is : 2 5 16 23 45 48 80 81 89
Descinding Order is : 89 81 80 48 45 23 16 5 2
Note: You can use Math.ranodm instead of adding manual numbers. Let me know if I need to change the code...
Good Luck... Cheers!!!
int[] array = {2, 3, 4, 5, 3, 4, 2, 34, 2, 56, 98, 32, 54};
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array.length; j++) {
if (array[i] < array[j]) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
}
}
Here is how to use this in your program:
public static void main(String args[])
{
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Arrays.sort(array);
System.out.println(array[0] +" " + array[1] +" " + array[2] +" " + array[3]
+" " + array[4] +" " + array[5]+" " + array[6]+" " + array[7]+" "
+ array[8]+" " + array[9] );
}
just FYI, you can now use Java 8 new API for sorting any type of array using parallelSort
parallelSort uses Fork/Join framework introduced in Java 7 to assign the sorting tasks to multiple threads available in the thread pool.
the two methods that can be used to sort int array,
parallelSort(int[] a)
parallelSort(int[] a,int fromIndex,int toIndex)
Java 8 provides the option of using streams which can be used to sort int[] array as:
int[] sorted = Arrays.stream(array).sorted().toArray(); // option 1
Arrays.parallelSort(array); //option 2
As mentioned in doc for parallelSort :
The sorting algorithm is a parallel sort-merge that breaks the array
into sub-arrays that are themselves sorted and then merged. When the
sub-array length reaches a minimum granularity, the sub-array is
sorted using the appropriate Arrays.sort method. If the length of the
specified array is less than the minimum granularity, then it is
sorted using the appropriate Arrays.sort method. The algorithm
requires a working space no greater than the size of the original
array. The ForkJoin common pool is used to execute any parallel tasks.
So if the input array is less than granularity (8192 elements in Java 9 and 4096 in Java 8 I believe), then parallelSort simply calls sequential sort algorithm.
Just in case we want to reverse sort the integer array we can make use of comparator as:
int[] reverseSorted = IntStream.of(array).boxed()
.sorted(Comparator.reverseOrder()).mapToInt(i -> i).toArray();
Since Java has no way to sort primitives with custom comparator, we have to use intermediate boxing or some other third party library which implements such primitive sorting.
You may use Arrays.sort() function.
sort() method is a java.util.Arrays class method.
Declaration : Arrays.sort(arrName)
Simply do the following before printing the array:-
Arrays.sort(array);
Note:-
you will have to import the arrays class by saying:-
import java.util.Arrays;
If you want to build the Quick sort algorithm yourself and have more understanding of how it works check the below code :
1- Create sort class
class QuickSort {
private int input[];
private int length;
public void sort(int[] numbers) {
if (numbers == null || numbers.length == 0) {
return;
}
this.input = numbers;
length = numbers.length;
quickSort(0, length - 1);
}
/*
* This method implements in-place quicksort algorithm recursively.
*/
private void quickSort(int low, int high) {
int i = low;
int j = high;
// pivot is middle index
int pivot = input[low + (high - low) / 2];
// Divide into two arrays
while (i <= j) {
/**
* As shown in above image, In each iteration, we will identify a
* number from left side which is greater then the pivot value, and
* a number from right side which is less then the pivot value. Once
* search is complete, we can swap both numbers.
*/
while (input[i] < pivot) {
i++;
}
while (input[j] > pivot) {
j--;
}
if (i <= j) {
swap(i, j);
// move index to next position on both sides
i++;
j--;
}
}
// calls quickSort() method recursively
if (low < j) {
quickSort(low, j);
}
if (i < high) {
quickSort(i, high);
}
}
private void swap(int i, int j) {
int temp = input[i];
input[i] = input[j];
input[j] = temp;
}
}
2- Send your unsorted array to Quicksort class
import java.util.Arrays;
public class QuickSortDemo {
public static void main(String args[]) {
// unsorted integer array
int[] unsorted = {6, 5, 3, 1, 8, 7, 2, 4};
System.out.println("Unsorted array :" + Arrays.toString(unsorted));
QuickSort algorithm = new QuickSort();
// sorting integer array using quicksort algorithm
algorithm.sort(unsorted);
// printing sorted array
System.out.println("Sorted array :" + Arrays.toString(unsorted));
}
}
3- Output
Unsorted array :[6, 5, 3, 1, 8, 7, 2, 4]
Sorted array :[1, 2, 3, 4, 5, 6, 7, 8]
We can also use binary search tree for getting sorted array by using in-order traversal method. The code also has implementation of basic binary search tree below.
class Util {
public static void printInorder(Node node)
{
if (node == null) {
return;
}
/* traverse left child */
printInorder(node.left);
System.out.print(node.data + " ");
/* traverse right child */
printInorder(node.right);
}
public static void sort(ArrayList<Integer> al, Node node) {
if (node == null) {
return;
}
/* sort left child */
sort(al, node.left);
al.add(node.data);
/* sort right child */
sort(al, node.right);
}
}
class Node {
Node left;
Integer data;
Node right;
public Node(Integer data) {
this.data = data;
}
public void insert(Integer element) {
if(element.equals(data)) {
return;
}
// if element is less than current then we know we will insert element to left-sub-tree
if(element < data) {
// if this node does not have a sub tree then this is the place we insert the element.
if(this.left == null) {
this.left = new Node(element);
} else { // if it has left subtree then we should iterate again.
this.left.insert(element);
}
} else {
if(this.right == null) {
this.right = new Node(element);
} else {
this.right.insert(element);
}
}
}
}
class Tree {
Node root;
public void insert(Integer element) {
if(root == null) {
root = new Node(element);
} else {
root.insert(element);
}
}
public void print() {
Util.printInorder(root);
}
public ArrayList<Integer> sort() {
ArrayList<Integer> al = new ArrayList<Integer>();
Util.sort(al, root);
return al;
}
}
public class Test {
public static void main(String[] args) {
int [] array = new int[10];
array[0] = ((int)(Math.random()*100+1));
array[1] = ((int)(Math.random()*100+1));
array[2] = ((int)(Math.random()*100+1));
array[3] = ((int)(Math.random()*100+1));
array[4] = ((int)(Math.random()*100+1));
array[5] = ((int)(Math.random()*100+1));
array[6] = ((int)(Math.random()*100+1));
array[7] = ((int)(Math.random()*100+1));
array[8] = ((int)(Math.random()*100+1));
array[9] = ((int)(Math.random()*100+1));
Tree tree = new Tree();
for (int i = 0; i < array.length; i++) {
tree.insert(array[i]);
}
tree.print();
ArrayList<Integer> al = tree.sort();
System.out.println("sorted array : ");
al.forEach(item -> System.out.print(item + " "));
}
}
MOST EFFECTIVE WAY!
public static void main(String args[])
{
int [] array = new int[10];//creates an array named array to hold 10 int's
for(int x: array)//for-each loop!
x = ((int)(Math.random()*100+1));
Array.sort(array);
for(int x: array)
System.out.println(x+" ");
}
Be aware that Arrays.sort() method is not thread safe: if your array is a property of a singleton, and used in a multi-threaded enviroment, you should put the sorting code in a synchronized block, or create a copy of the array and order that copy (only the array structure is copied, using the same objects inside).
For example:
int[] array = new int[10];
...
int[] arrayCopy = Arrays.copyOf(array , array .length);
Arrays.sort(arrayCopy);
// use the arrayCopy;
I've just been looking at the following piece of code
package test;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(final String[] args) {
final int sizeA = 3;
final int sizeB = 5;
final List<int[]> combos = getAllCombinations(sizeA-1, sizeB);
int counter = 1;
for(final int[] combo : combos) {
System.out.println("Combination " + counter);
System.out.println("--------------");
for(final int value : combo) {
System.out.print(value + " ");
}
System.out.println();
System.out.println();
++counter;
}
}
private static List<int[]> getAllCombinations(final int maxIndex, final int size) {
if(maxIndex >= size)
throw new IllegalArgumentException("The maximum index must be smaller than the array size.");
final List<int[]> result = new ArrayList<int[]>();
if(maxIndex == 0) {
final int[] array = new int[size];
Arrays.fill(array, maxIndex);
result.add(array);
return result;
}
//We'll create one array for every time the maxIndex can occur while allowing
//every other index to appear, then create every variation on that array
//by having every possible head generated recursively
for(int i = 1; i < size - maxIndex + 1; ++i) {
//Generating every possible head for the array
final List<int[]> heads = getAllCombinations(maxIndex - 1, size - i);
//Combining every head with the tail
for(final int[] head : heads) {
final int[] array = new int[size];
System.arraycopy(head, 0, array, 0, head.length);
//Filling the tail of the array with i maxIndex values
for(int j = 1; j <= i; ++j)
array[size - j] = maxIndex;
result.add(array);
}
}
return result;
}
}
I'm wondering, how do I eliminate recursion from this, so that it returns a single random combination, rather than a list of all possible combinations?
Thanks
If I understand your code correctly your task is as follows: give a random combination of numbers '0' .. 'sizeA-1' of length sizeB where
the combination is sorted
each number occurs at least once
i.e. in your example e.g. [0,0,1,2,2].
If you want to have a single combination only I'd suggest another algorithm (pseudo-code):
Randomly choose the step-up positions (e.g. for sequence [0,0,1,1,2] it would be steps (1->2) & (3->4)) - we need sizeA-1 steps randomly chosen at sizeB-1 positions.
Calculate your target combination out of this vector
A quick-and-dirty implementation in java looks like follows
// Generate list 0,1,2,...,sizeB-2 of possible step-positions
List<Integer> steps = new ArrayList<Integer>();
for (int h = 0; h < sizeB-1; h++) {
steps.add(h);
}
// Randomly choose sizeA-1 elements
Collections.shuffle(steps);
steps = steps.subList(0, sizeA - 1);
Collections.sort(steps);
// Build result array
int[] result = new int[sizeB];
for (int h = 0, o = 0; h < sizeB; h++) {
result[h] = o;
if (o < steps.size() && steps.get(o) == h) {
o++;
}
}
Note: this can be optimized further - the first step generates a random permutation and later strips this down to desired size. Therefore it is just for demonstration purpose that the algorithm itself works as desired.
This appears to be homework. Without giving you code, here's an idea. Call getAllCombinations, store the result in a List, and return a value from a random index in that list. As Howard pointed out in his comment to your question, eliminating recursion, and returning a random combination are separate tasks.