Docsity

COCKTAIL SORT STRAND SORT, Monografías, Ensayos de Programación Java

Vista previa parcial del texto

¡Descarga COCKTAIL SORT STRAND SORT y más Monografías, Ensayos en PDF de Programación Java solo en Docsity!

COCKTAIL SORT STRAND

SORT

UNIVERSIDAD: UNIVERSIDAD PRIVADA DEL VALLE NOMBRE: MAYLI ARIANA MERLO MAYTA SEMESTRE: 3 SEMESTRE DOCENTE: ING. DIEGO PARRAGA MENCHACA CARRERA: ING. CIVIL FECHA:10-06-

COMPUTACION

PARALELO A

EXPLICACION DE LOS ALGORITMOS:

STRAND SORT

Es un algoritmo de ordenación recursiva que clasifica los elementos de una lista en orden creciente. Tiene O (n 2 ) la peor complejidad de tiempo que ocurre cuando la lista de entrada está ordenada inversamente. Tiene una complejidad de tiempo de mejor caso de O (n) que ocurre cuando la entrada es una lista que ya está ordenada. La ordenación de cadena no está en su lugar ya que su complejidad espacial es O (n).  El algoritmo primero mueve el primer elemento de una lista a una sublista.Luego compara el último elemento en la sublista con cada elemento subsiguiente en la lista original.Una vez que hay un elemento en la lista original que es mayor que el último elemento en la sublista, el elemento se elimina de la lista original y se agrega a la sublista.Este proceso continúa hasta que el último elemento en la sublista se compara con los elementos restantes en la lista original.La sublista se fusiona en una nueva lista.Repita este proceso y combine todas las sublistas hasta que todos los elementos estén ordenados. Este algoritmo se denomina ordenación de hebras porque hay hebras de elementos ordenados dentro de los elementos no ordenados que se eliminan de uno en uno. Este algoritmo también se usa en J Sort para menos de 40 elementos. Dada una lista de elementos, ordénelos en orden creciente. Ejemplos: Entrada: ip [] = {10, 5, 30, 40, 2, 4, 9} Salida: op [] = {2, 4, 5, 9, 10, 30, 40} Entrada: ip [] = {1, 10, 7} Salida: op [] = {1, 7, 10} Strand Sort es un algoritmo de ordenación que funciona en tiempo O (n) si la lista ya está ordenada y funciona en O (n * n) en el peor de los casos.

filter_none editar play_arrow brillo_ // CPP program to implement Strand Sort #include <bits/stdc++.h> using namespace std; // A recursive function to implement Strand // sort. // ip is input list of items (unsorted). // op is output list of items (sorted) void strandSort(list &ip, list &op) { // Base case : input is empty if (ip.empty()) return; // Create a sorted sublist with // first item of input list as // first item of the sublist list sublist; sublist.push_back(ip.front()); ip.pop_front(); // Traverse remaining items of ip list for (auto it = ip.begin(); it != ip.end(); ) { // If current item of input list // is greater than last added item // to sublist, move current item // to sublist as sorted order is // maintained. if (it > sublist.back()) { sublist.push_back(it); // erase() on list removes an // item and returns iterator to // next of removed item. it = ip.erase(it); } // Otherwise ignore current element else

it++; } // Merge current sublist into output op.merge(sublist); // Recur for remaining items in // input and current items in op. strandSort(ip, op); } // Driver code int main(void) { list ip{10, 5, 30, 40, 2, 4, 9}; // To store sorted output list list op; // Sorting the list strandSort(ip, op); // Printing the sorted list for (auto x : op) cout << x << " "; return 0; } Salida: 2 4 5 9 10 30 40 Descripción del algoritmo del libro, IT Enabled Practices y Emerging Management Paradigms. [1] 1 paquete strandSort ; 2 3 **import java.util. *** ; 4 4 5 5 público de clase strandSort { 6 6 LinkedList estático < Integer > solList = new LinkedList < Integer > (); 7 7 estático int k = 0 ; 8

47 // lista de soluciones en orden secuencial 48 si ( k == 0 ) { 49 for ( int i = 0 ; i < subList. size (); i ++ ) { 50 51 solList. add ( subList. get ( i )); 52 k = k + 1 ; 53 } 54 55 } 56 57 // Caso 2: después de la primera llamada recursiva, 58 // fusionar la sublista con la lista de soluciones. 59 // Esto funciona comparando el elemento más grande en la sublista (que siempre es el último elemento) 60 60 // con el primer elemento en la lista de soluciones. 61 más { 62 62 int subEnd = subList. tamaño () - 1 ; 63 int solStart = 0 ; 64 while (! subList. isEmpty ()) { sesenta y cinco 66 if ( subList. get ( subEnd ) > solList. get ( solStart )) { 67 solStart ++ ; 68 69 } más { 70 solList. add ( solStart , subList. get ( subEnd )); 71 sublista. eliminar ( subEnd ); 72 subEnd - ; 73 solStart = 0 ; 74 } 75 76 } 77 78 } 79 80 strandSortIterative ( origList ); 81 } 82 83 } 84 85 public static void main ( String [] args ) {

86 // Crear una nueva lista vinculada de enteros 87 LinkedList < Integer > origList = new LinkedList < Integer > (); 88 89 // Agregue los siguientes enteros a la lista vinculada: {5, 1, 4, 2, 0, 9, 6, 3, 8, 7} 90 91 91 OrigList. agregar ( 5 ); 92 OrigList. agregar ( 1 ); 93 OrigList. agregar ( 4 ); 94 OrigList. agregar ( 2 ); 95 OrigList. agregar ( 0 ); 96 OrigList. agregar ( 9 ); 97 OrigList. agregar ( 6 ); 98 OrigList. agregar ( 3 ); 99 OrigList. agregar ( 8 ); 100 OrigList. agregar ( 7 ); 101 102 strandSortIterative ( origList ); 103 // Imprime la lista de soluciones 104 for ( int i = 0 ; i < solList. size (); i ++ ) { 105 Sistema. a cabo. println ( solList. get ( i )); 106 } 107 108 } 109 110 } // Driver code int main() { int arr[] = { 5, 1, 4, 2, 8, 0, 2 }; int n = sizeof(arr) / sizeof(arr[0]); CocktailSort(a, n); printf("Sorted array :\n"); printArray(a, n); return 0; }

Primer pase hacia atrás: (1 4 2 5 0 2 8)? (1 4 2 5 0 2 8) (1 4 2 5 0 2 8)? (1 4 2 0 5 2 8), Cambiar desde 5> 0 (1 4 2 0 5 2 8)? (1 4 0 2 5 2 8), ¿Cambiar desde 2> 0 (1 4 0 2 5 2 8)? (1 0 4 2 5 2 8), ¿Cambiar desde 4> 0 ( 1 0 4 2 5 2 8)? ( 0 1 4 2 5 2 8), Intercambiar desde 1> 0 Después del primer paso hacia atrás, el elemento más pequeño de la matriz estará presente en el primer índice de la matriz. Segundo pase adelantado: (0 1 4 2 5 2 8)? (0 1 4 2 5 2 8) (0 1 4 2 5 2 8)? (0 1 2 4 5 2 8), ¿Cambiar desde 4> 2 (0 1 2 4 5 2 8)? (0 1 2 4 5 2 8) (0 1 2 4 5 2 8)? (0 1 2 4 2 5 8), Intercambiar desde 5> 2 Segundo pase hacia atrás: (0 1 2 4 2 5 8)? (0 1 2 2 4 5 8), Intercambiar desde 4> 2 Ahora, la matriz ya está ordenada, pero nuestro algoritmo no sabe si está completa. El algoritmo necesita completar todo este pase sin ningún intercambio para saber que está ordenado. (0 1 2 2 4 5 8)? (0 1 2 2 4 5 8) (0 1 2 2 4 5 8)? (0 1 2 2 4 5 8) A continuación se muestra la implementación del algoritmo anterior: // C++ implementation of Cocktail Sort #include <bits/stdc++.h> using namespace std; // Sorts arrar a[0..n-1] using Cocktail sort void CocktailSort(int a[], int n) { bool swapped = true; int start = 0; int end = n - 1; while (swapped) { // reset the swapped flag on entering // the loop, because it might be true from // a previous iteration. swapped = false; // loop from left to right same as // the bubble sort for (int i = start; i < end; ++i) {

if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // if nothing moved, then array is sorted. if (!swapped) break; // otherwise, reset the swapped flag so that it // can be used in the next stage swapped = false; // move the end point back by one, because // item at the end is in its rightful spot --end; // from right to left, doing the // same comparison as in the previous stage for (int i = end - 1; i >= start; --i) { if (a[i] > a[i + 1]) { swap(a[i], a[i + 1]); swapped = true; } } // increase the starting point, because // the last stage would have moved the next // smallest number to its rightful spot. ++start; } } /* Prints the array */ void printArray(int a[], int n) { for (int i = 0; i < n; i++) printf("%d ", a[i]); printf("\n"); } // Driver code int main()