So the purpose of this program is to selectively sort a random array of integers form largest to smallest. To do this, I needed to keep swapping the first element with the largest element. I think my methods are correct, but I am fairly new to Java and not sure what to call in main in order to execute my methods correctly. Thank you in advance!
package sortarray;
public class SortArray {
public static int randomInt(int low, int high) {
double e;
double x=Math.random();
e=low+x*(high-low);
return (int)e;
}
public static int[] randomIntArray(int n) {
int[] a = new int[n];
for(int i = 0; i < a.length; i++) {
a[i] = randomInt(-5, 15);
}
return a;
}
public static int indexOfMaxInRange(int[] a, int low, int high) {
int index = low;
for (int i = low + 1; i < a.length; i++) {
if (a[i] > a[index]) {
index = i;
}
}
return index;
}
public static void swapElement(int[] a, int index1, int index2) {
int temp = a[index1];
a[index1] = a[index2];
a[index2] = temp;
}
public static void sort(int[] a) {
int length = a.length;
//use length-1 because do not need to swap last element with itself
for (int i = 0; i < length-1; i++) {
int indexOfMax = indexOfMaxInRange(a, i, length-1);
swapElement(a, i, indexOfMax);
}
}
public static void printArray(int[] a) {
for(int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}
public static void main(String[] args) {
int[] array = randomIntArray(30);
printArray();
}
}
To sort the array, you simply need to call the following:
sort(array);
Then, you can print the array again to verify that it is sorted with:
printArray(array);
Also you can call the method sort() within of printArray() method, so when you call printArray() it will print sorted:
...
public static void printArray(int[] a) {
sort(a);
for (int i = 0; i < a.length; i++) {
System.out.print(" " + a[i]);
}
}
public static void main(String[] args) {
int[] array = randomIntArray(30);
printArray(array);
}
...
Here is my code that I posted on Code Review. This sort an array of String, But you can put integer instead.
https://codereview.stackexchange.com/questions/160243/sort-a-given-string-in-ascending-order
Given string
[H, B, D, G, F, E, A, C]
Output
[A, B, C, D, E, F, G, H]
public class sortArray {
public static void sort (String[] str)
{
int lastPos = str.length - 1;
int minPos = 0;
String s = "";
for (int i = 0; i < lastPos; i++)
{
minPos = i;
for (int j = i + 1; j <= lastPos; j++)
if (str[j].compareTo (str[minPos]) < 0)
minPos = j;
if (minPos != i)
{
s = str[i];
str[i] = str[minPos];
str[minPos] = s;
}
}
}
public static void main(String[] args){
String[] str = {"H", "B", "D", "G","F", "E", "A", "C"};
sort(str);
System.out.println(Arrays.toString(str));
}
}
There must have the arguments in the methods you use,
you should put the array in the ( )
you can use inbuilt function of Arrays. Simply call the inbuilt method and pass your array.
Arrays.sort(pass your array here).
If you dot want to use inbuilt method please refer this link.
Java : Sort integer array without using Arrays.sort()
Related
The purpose of this project is to create two arrays of random numbers and run a quick sort and heap sort of them. Keep track of the number of comparison's and then compare them. Both sorts work, but my heap sort wont keep track of the comparison's. it just says 0. My quick sort works and puts the comparisons in an array. How do i fix this?
package sorting;
import java.util.Arrays;
//import java.util.Random;
import java.util.*;
public class project2
{
static int [] heap_sort_comparison = new int[21];
static int [] quick_sort_comparison = new int[21];
static int [] array1 = new int [20];
static int [] array2 = new int [20];
static int compares = 0;
static int heap_compares = 0;
private static void quickSort(int[] array1, int l, int h) {
if(l < h ) {
compares++;
int position = partition(array1, l, h);
quickSort(array1,l, position -1);
quickSort(array1, position +1, h);
}
}
private static int partition(int[] array1, int i, int j) {
int pivot = array1[j] -1;
int small = i -1;
for(int k = i; k < j; k++) {
if(array1[k] <= pivot) {
compares++;
small++;
swap(array1, k, small);
}
}
swap(array1, j, small + 1);
//System.out.println("Pivot = " + array1[small + 1]);
print_quick_sort(array1);
return small + 1;
}
public static void swap(int[] array1, int a, int b) {
int temp;
temp = array1[a];
array1[a] = array1[b];
array1[b] = temp;
}
public static void print_quick_sort(int[] array1) {
for(int i = 0; i < array1.length; i++) {
System.out.print(array1[i] + " ");
}
System.out.println();
}
//HEAP SORT
public void build(int array2[]) {
int length = array2.length;
for(int i = length/2-2; i >=0; i--) {
bubble_down(array2, i, array2.length-1);
heap_compares++;
}
for(int i = length-1; i>= 0; i--) {
swap2(array2, 0,i);
bubble_down(array2,i,0);
heap_compares++;
}
}
void bubble_down(int[] array2, int parent, int size) {
int left = parent*2+1;
int right = 2*parent+2;
int largest = 0;
if(left <= size && array2[left] > array2[largest]) {
largest = left;
heap_compares++;
}
if(right <= size && array2[right] > array2[largest]) {
largest = right;
heap_compares++;
}
if(largest != parent) {
swap2(array2,parent, largest);
bubble_down(array2,largest,size);
heap_compares++;
}
}
public static void swap2(int[] array2, int a, int b) {
int temp = array2[a];
array2[a] = array2[b];
array2[b] = temp;
}
public static void print_heap_sort(int[] array2) {
for(int i = 0; i < array2.length; i++) {
System.out.print(array2[i] + " ");
}
System.out.println();
}
public static void main(String[] args) {
for(int x = 0; x < 20; x++) {
for(int y = 0; y < 20; y++) {
for(int i = 0; i < array1.length; i++) {
array1[i] = array2[i]= (int)(Math.random()*20 + 0);
}
System.out.println("Numbers Generated in Array 1: " + Arrays.toString(array1));
System.out.println("");
System.out.println("Numbers Generated in Array 2: " + Arrays.toString(array2));
System.out.println("");
//quickSort
print_quick_sort(array1);
quickSort(array1, 0, array1.length -1);
System.out.println("The number of comparisons in quick sort: "+ compares);
System.out.println("=============================");
quick_sort_comparison[x] = compares;
compares = 0;
System.out.println("Array of quick sort comparison's: ");
System.out.println(Arrays.toString(quick_sort_comparison));
System.out.println("=============================");
//Heap Sort
System.out.println("Before Heap Sort: ");
System.out.println(Arrays.toString(array2));
heap_sort_comparison[y] = heap_compares;
heap_compares = 0;
HeapSort ob = new HeapSort();
ob.sort(array2);
System.out.println("Sorted array is (heap Sort): ");
print_heap_sort(array2);
System.out.println("=============================");
System.out.println("Array of heap sort comparison's: " + heap_compares);
System.out.println(Arrays.toString(heap_sort_comparison));
}
}
}
}
You do not even call the HeapSort method that you've built.
look here...
HeapSort ob = new HeapSort();
ob.sort(array2);
I think you are trying to use a built in sorting method from HeapSort class, So how do you think the counter heap_compares will increase!
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);
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;
}
I am unclear as to what this is asking me to do, and how I execute it, in reference to the int [] copyAndReplaceLessThan(int []a, int b) method. Any help would be greatly appreciated, thanks.
Task:
Test this method in main. Print both the original array and the returned array which the method, copyAndReplaceLessThan, returns. Since this method returns a value (an integer array), you need to “catch” the returned value in a local variable (of type int []) in the calling method (main).
For example: Assuming you pass the array “x” to the method and use array “y” to catch the returned value. Print x before you call the method and then print both x and y after calling the method.
public class ArrayExamples{
public static void swapInts(int a, int b){
int temp;
temp = a;
a = b;
b = temp;
}
public static void swapIntArrays(int [] a, int [] b){
int x;
for (int i=0; i<a.length; i++){
x = a[i];
a[i]=b[i];
b[i]=x;
}
}
public static void printArray(int[] a){
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i] + " ");
}
System.out.println("");
}
public static void main(String args[]){
int [] one ={3,4};
int [] two ={7,8};
printArray(one);
printArray(two);
swapIntArrays(one,two);
printArray(one);
printArray(two);
System.out.println();
int [] x ={3,45,17,2,-1,44,9,23,67,2,-6,-23,-100,12,5,1212};
int b = 12;
printArray(x);
replaceLessThan(x,b);
printArray(x);
printArray(x);
copyAndReplaceLessThan(x,b);
printArray(x);
printArray(y);
}
public static void replaceLessThan(int []a, int b){
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
}
else{
a[i] = a[i];
}
}
}
public static int[] copyAndReplaceLessThan(int []a, int b){
int []x = a;
int[]y = x;
for(int i=0; i < a.length; i++){
if(a[i] < b){
a[i] = b;
y[i] = b;
}
else{
a[i] = a[i];
y[i] = a[i];
}
}
return y;
}
}
public static int[] copyAndReplaceLessThan(int[] a, int b)
{
int[] x = a.clone();
for (int i = 0; i < x.length; i++)
{
if (x[i] < b)
{
x[i] = b;
}
}
return x;
}
Some problems:
You're supposed to leave the original array unaltered, yet you're setting its elements with
a[i] = b;
And there's no point to doing this
a[i] = a[i];
as you're just resetting the value to itself.
But your biggest problem is that you're not creating a new array, as you're supposed to. Instead, your "new" array (y) is referring to the original one (a), and therefore any changes to y are actually being made in the original.
I also recommend that you either test or try a for nullness.
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]);