
















Studia grazie alle numerose risorse presenti su Docsity
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Prepara i tuoi esami
Studia grazie alle numerose risorse presenti su Docsity
Prepara i tuoi esami con i documenti condivisi da studenti come te su Docsity
Trova i documenti specifici per gli esami della tua università
Preparati con lezioni e prove svolte basate sui programmi universitari!
Rispondi a reali domande d’esame e scopri la tua preparazione
Riassumi i tuoi documenti, fagli domande, convertili in quiz e mappe concettuali
Studia con prove svolte, tesine e consigli utili
Togliti ogni dubbio leggendo le risposte alle domande fatte da altri studenti come te
Esplora i documenti più scaricati per gli argomenti di studio più popolari
Ottieni i punti per scaricare
Guadagna punti aiutando altri studenti oppure acquistali con un piano Premium
Diverse soluzioni per l'implementazione dell'algoritmo di ordinamento insertion sort in java. Le soluzioni sono state valutate in base alla leggibilità del codice, all'utilizzo di commenti, alla presenza di metodi di astrazione e alla corretta implementazione dell'algoritmo. La soluzione migliore presenta un'implementazione concisa e corretta dell'algoritmo, con l'utilizzo di commenti per spiegare le astrazioni e i contratti. La soluzione intermedia presenta un'implementazione buona che ha i contratti, ma non ci sono commenti che descrivono le astrazioni/i contratti. La soluzione senza specifiche non ordina l'array. La soluzione con espressione condizionale presenta un'implementazione poco leggibile e error-prone. Le altre soluzioni presentano problemi di leggibilità, assenza di metodi di astrazione e duplicazione di codice tra i due metodi di ordinamento.
Tipologia: Prove d'esame
1 / 24
Questa pagina non è visibile nell’anteprima
Non perderti parti importanti!

















Prendere il seguente esempio di codice Java e modificarlo in modo da realizzarne uno che abbia (almeno) un metodo in grado di ordinare o in maniera crescente o in maniera decrescente i dati.
Tale metodo deve poter essere invocato indicando, in qualche modo, la direzione di ordinamento.
(Suggerimento: usare qualsiasi tipo di astrazione sembri essere adatto; anche più di uno.) public class MyInsertionSort {
static int[] arr1 = {10,34,2,56,7,67,88,42}; static int temp;
public static void main(String a[]){ for (int i = 1; i < arr1.length; i++) { for (int j = i ; j > 0 ; j--){ if (arr1[j] < arr1[j-1]){ temp = arr1[j]; arr1[j] = arr1[j-1]; arr1[j-1] = temp; } } } for (int i:arr1){ System.out.print(i); System.out.print(", "); } } }
Nel seguito fornisco alcuni esempi di commenti di vari tipi di soluzione. Cercando di evidenziare le cose positive e quelle negative.
public static void sort(int[] arr1, int x) { // ordina in modo crescente se x= if (x == 0) { for (int i = 1; i < arr1.length; i++) { for (int j = i; j > 0; j--) { if (arr1[j] < arr1[j - 1]) { temp = arr1[j]; arr1[j] = arr1[j - 1]; arr1[j - 1] = temp; } } } for (int i : arr1) { System.out.print(i); System.out.print(", "); } } else if (x == 1) { // ordina in modo decrescente se x= for (int i = 1; i < arr1.length; i++) { for (int j = i; j > 0; j--) { if (arr1[j] > arr1[j - 1]) { temp = arr1[j]; arr1[j] = arr1[j - 1]; arr1[j - 1] = temp; } } }
Miei commenti
public static void main(String a[]) throws IOException{
int[] array = {130,6,59,81,728,142,32,62,94,553,1662,1,43,5,522}; InputStreamReader input = new InputStreamReader(System.in); char choice;
System.out.println(); System.out.println("Benvenuto! Ho in memoria un vettore. In che direzione lo vuoi or
System.out.println("Digita 'C' per l'ordine crescente oppure digita 'D' per l'ordine choice = (char)input.read();
chooseSort (array, choice);
printArray(array); } // end main
/** * chooseSort int [] a ; It allows you to choose the sort direction * @param a an array of integers , REQUIRE to have 1 or more elements * @param c is a char variable , REQUIRE to be a valid character_. **/_ private static void chooseSort (int [] a, char c){
if (c=='C'){ ascendingSort(a); }
else if (c=='D'){ descendingSort(a); }
else { System.out.print("Errore nell'input immesso. Ricontrolla ciò che ha System.exit(0); }
}
* ascendingSort int [] a ; MODIFY the array a by sort ascending * @param vector an array of integers , REQUIRE to have 1 or more elements
Miei commenti
public class MyInsertionSort { static int[] arr1 = {10,34,2,56,7,67,88,42}; //static int temp; Arrays.sort(arr1);
for (int i:arr1){ System.out.print(i); System.out.print(", "); }
/* public static void main(String a[]){ for (int i = 1; i < arr1.length; i++) { for(int j = i ; j > 0 ; j--){ swap(j); } } stampa(); }
private static void stampa() { for(int i:arr1){ System.out.print(i); System.out.print(", "); } }
private static void swap(int j) { if(arr1[j] < arr1[j-1]){ temp = arr1[j]; arr1[j] = arr1[j-1]; arr1[j-1] = temp; } }*/ }
Miei commenti
la sua soluzione:
/** * This class permits to order a given array by invoking the method doInsertionSort (...); */ public class MyInsertionSort {
private static final Boolean ASCENDING = true ; private static final Boolean DESCENDING = false ; private static int[] arr;
* Take in input an array , set it and invoke the method doInsertionSort ( Boolean mode ); * @param array is an array of integer , REQUIRE to be not null ; * @param mode is a boolean variable that determinate the order ; use the static constan */ public static void doInsertionSort(int[] array, Boolean mode) { setArray(array); doInsertionSort(mode); }
/** * Use the set arr and MODIFY his order in relation of the input mode ( ascending or des * @param mode is a boolean variable that determinate the order ; use the static constan / /* * @param mode */ public static void doInsertionSort(Boolean mode) { if (arr.length > 1) { for (int i = 1; i < arr.length; i++) { for (int j = i ; j > 0 ; j--) { if ((mode)? (arr[j] < arr[j-1]) : (arr[j] > arr[i])) { // Contracted fo swap(arr, j, j-1); } } } } }
/** * Swap the position of two elements ; MODIFY array ;
* @param array of integer , REQUIRE to have 2 or more elements ; * @param i index of array ; * @param j index of array ; */ public static void swap(int[] array, int i, int j) { int temp = array[i]; array[i] = array[j]; array[j] = temp; }
* set the array input in the static variable ; MODIFY arr ; * @param array is an array of integer ; */ public static void setArray(int[] array) { arr = array; }
* show at terminal the static variable arr ; as the EFFECT to show arr ; */ public static void toMonitor() { System.out.print(arr[0]); for (int i = 1; i < arr.length; i++) { System.out.print(", "); System.out.print(arr[i]); } }
/** * @return the static constant ASCENDING ; */ public static boolean getAscending() { return ASCENDING; }
/** * @return the static constant DESCENDING ; */ public static boolean getDescending() { return DESCENDING; }
/**
public class insert {
static int[] arr1 = {10,34,2,56,7,67,88,42}; static int temp;
public static void main(String[] args){ for (int i = 1; i < arr1.length; i++) { for (int j = i ; j > 0 ; j--){ if (op (arr1[j],arr1[j-1],args[0])){ temp = arr1[j]; arr1[j] = arr1[j-1]; arr1[j-1] = temp; } } } for (int i:arr1){ System.out.print(i); System.out.print(", ");}
}
// il seguente codice confronta i parametri e in base al metodo di ordinamento fa esegui
public static boolean op(int j,int j1,String arg){ if ((arg.equals("crescente")&& (j<j1) )||(arg.equals("decrescente")&& (j>j1) )) return true ; else return false ;
} }
Miei commenti
public class Ordninamento { static int vett[], l, n;
_/*Questo metodo crea l'array da ordinare chiedendo al utente di inserire il
*/_ private static void CreaVettDaOrdinare(){
int m, i = 0; Scanner buff = new Scanner(System.in); System.out.println("Inserisci il numero di elementi da ordinare"); l = buff.nextInt(); vett = new int [l]; System.out.println("Inserisci i numeri da ordinare");
while (i < l){ m = buff.nextInt(); vett[i] = m; i++; } } _/*
Scanner input = new Scanner(System.in); System.out.println("Inserisci 0 per avere un ordinamento crescente oppure 1 per aver n = input.nextInt();
if (n == 0){ Crescente(vett); } else { Decrescente(vett); }
}
for (int i:vett){ System.out.print(i); System.out.print(", "); } } }
Miei commenti
public class MyInsertionSort{ static int[] arr1 = {10,34,2,56,7,67,88,42} ; static int temp ;
public static void main(String[] args){
// variables Scanner in = new Scanner(System.in) ; boolean flag = false ; String choice = "_" ; boolean ascending = true ;
// choice order do { System.out.print("type\n a , for an ascending sort,\n d , for a decreasing sort. choice = in.next() ; if (choice.equals("a")){ flag = true ; } if (choice.equals("d")){ flag = true ; ascending = false ; } } while (!flag) ;
// execution order if (ascending){ ascendingSort() ; } else { decreasingSort() ; }
// print sorted array for (int i:arr1){ System.out.print(i); System.out.print(", "); } System.out.print("\n");
} // end main
private static void ascendingSort(){ for (int i=1;i<arr1.length;i++){
Le seguenti due soluzioni sono “orientate agli oggetti”, la prima possibile in java 7 e 8, la seconda solo con java 8.
package it.uniud.poo.abstractions;
/** * @author giorgio * Example with parametric choice of sort direction_.
*/_ public class MySortAnonymousClasses {
/** * Labels to specify order direction */ public enum sortDirection { INCREASING, DECREASING }
/** * Interface to be used as a parameter to * implement a particular kind of comparison * between int_. /_ interface IntComparator { _/* _ @param x __ @param y * @return true or false depending on what meaning we want to * give to compare_._ Eg_._ compare ( x , y ) can imply x <y, or x=2*y, or ...
* Run a simple example with two sorting procedures : up and down_. */_ public static void main (String a[]){ int[] arr1 = {10,34,2,56,7,67,88,42};
doParametricSort(arr1, sortDirection.INCREASING); System.out.format("Increasing: "); for (int i:arr1){ System.out.print(i); System.out.print(", "); } doParametricSort(arr1, sortDirection.DECREASING); System.out.format("\nDecreasing: "); for (int i:arr1){ System.out.print(i); System.out.print(", "); } } /** * sort the array a * MODIFY the array a so that values are ordered * @param a: an array of integers to be sorted * @param dir: the direction of the sort : INCREASING / DECREASING / /* * @param a */ private static void doParametricSort(int[] a, sortDirection dir) { IntComparator ic = null ; // the actual comparator that we will be using switch (dir) { case INCREASING: ic = new IntComparator() { @Override public boolean compare(int x, int y) { return (x < y); } }; break ;
case DECREASING: ic = new IntComparator() { @Override public boolean compare(int x, int y) { return (x > y); }