You are on page 1of 12

SHELL SORT

Public Sub shellSort()


Dim salto As Integer
Dim cambios As Integer
Dim aux As Integer
Dim i As Integer
salto = (arr.length / 2)
While salto <> 0
cambios = 1
While cambios <> 0
cambios = 0
For i = salto To arr.length - 1
If arr(i - salto) > arr(i) Then
aux = arr(i)
arr(i) = arr(i - salto)
arr(i - salto) = aux
cambios += 1
End If
Next
End While
salto /= 2
End While
End Sub


SELECCIN SORT
' array of integers to hold values
Private a As Integer() = New Integer(99) {}

' number of elements in array
Private x As Integer

' Selection Sort Algorithm
Public Sub sortArray()
Dim i As Integer, j As Integer
Dim min As Integer, temp As Integer

For i = 0 To x - 2
min = i

For j = i + 1 To x - 1
If a(j) < a(min) Then
min = j
End If
Next

temp = a(i)
a(i) = a(min)
a(min) = temp
Next
End Sub






INSERCION SHORT
array of integers to hold values
Private a As Integer() = New Integer(99) {}

' number of elements in array
Private x As Integer

' Insertion Sort Algorithm
Public Sub sortArray()
Dim i As Integer
Dim j As Integer
Dim index As Integer

For i = 1 To x - 1
index = a(i)
j = i

While (j > 0) AndAlso (a(j - 1) > index)
a(j) = a(j - 1)
j = j - 1
End While

a(j) = index
Next
End Sub

QUICKSORT
'Ordenacion rapida (QuickSort)
Public Shared Sub QuickSort(a As Integer())
QuickSort(0, a.Length - 1, a)
End Sub

Private Shared Sub QuickSort(ini As Integer, fin As Integer, a As Integer())
Dim left As Integer = ini
Dim right As Integer = fin
Dim mid As Integer = a((ini + fin) \ 2)

Do
'Este es el Partition
While a(left) < mid
left += 1
End While
While a(right) > mid
right -= 1
End While
If left <= right Then
'Intercambio los elementos
'si estan invertidos
Dim t As Integer = a(left)
a(left) = a(right)
a(right) = t
left += 1
right -= 1
End If
Loop While left <= right

'Ordeno recursivamente los dos subarreglos
If left < fin Then
QuickSort(left, fin, a)
End If
If right > ini Then
QuickSort(ini, right, a)
End If
End Sub
SHELL SORT














Merge sort
public class MergeSortTest {

public static final int max = 10;

public static void main(String[] args){

int[] toSortArray = new int[max];
//Required variables:


//End - Required Variables

for(int i = 0; i < max; i++){

toSortArray[i] = (int) (Math.random()*100);

}

System.out.println("The array to be sorted is:");

for(int i = 0; i < max; i++){

System.out.print(" | " + toSortArray[i]);
}
System.out.println(" | ");

//Beginning of the algorithm


mergeSortHelper(toSortArray,0,max-1);


// End of the algorithm

System.out.println("The sorted array is: ");

for(int i = 0; i < max; i++){

System.out.print(" | " + toSortArray[i]);
}

System.out.println(" | ");

}

private static void mergeSortHelper(int[] toSortArray, int first, int
last) {

partition(toSortArray, first, last);

}

private static void partition(int[] toSortArray, int first, int last)
{

int mid = (first+last)/2;

if(first<last){

partition(toSortArray,first,mid);
partition(toSortArray,mid+1,last);
merge(toSortArray,first,mid,last);

}

}

private static void merge(int[] toSortArray, int first, int mid, int
last) {

int[] newArray = new int[max];
int i, j, k;

i = first;
j = mid + 1;
k = 0;

while(i <= mid && j <= last){

if(toSortArray[i] < toSortArray[j]){

newArray[k] = toSortArray[i];
i++;
k++;

}else{

newArray[k] = toSortArray[j];
j++;
k++;

}

}

while(i <= mid){

newArray[k] = toSortArray[i];
i++;
k++;

}

while(j <= last){

newArray[k] = toSortArray[j];
j++;
k++;

}

for(i = first, j = 0; i <= last ; i++,j++){

toSortArray[i] = newArray[j];

}

}

}









Ordenacin por Combinacin - Merge Sort
El algoritmo de ordenacin por combinacin o Merge Sort, basado en la tcnica Divide y
Vencers, ordena recursivamente un conjunto de elementos dividindolo en dos, ordenando
cada una de estas partes en forma independiente y combinando los dos resultados.

Este cdigo en el lenguaje de programacin JAVA 1.6 recibe como entrada un arreglo de
nmeros enteros denominado v, lo parte utilizando el mtodo copyOfRange de la
clase java.util.Arrays, se llama recursivamente con cada una de las dos partes como
argumento y, una vez terminada la ordenacin de dichas partes, invoca al proceso de
combinacin de las dos respuestas implementado en el mtodo combinar, el cual recibe como
entrada el arreglo original y las dos mitades del mismo previamente ordenadas que sern
combinadas en el arreglo original.
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// Algoritmo de ordenacion por combinacion: Merge Sort
public static void ordenacionCombinacion(int[] v) {
final int N = v.length;
if(N<=1) return;
int mitad=N/2;
int[] izq = Arrays.copyOfRange(v, 0, mitad);
int[] der = Arrays.copyOfRange(v, mitad, N);
ordenacionCombinacion(izq);
ordenacionCombinacion(der);
combinar(v, izq, der);
}

public static void combinar(int[] resp, int[] izq, int[] der) {
int i = 0;
int j = 0;
for(int k=0; k<resp.length;k++) {
if(i>=izq.length) { resp[k]=der[j++]; continue; }
if(j>=der.length) { resp[k]=izq[i++]; continue; }
resp[k]=(izq[i]<der[j])?izq[i++]:der[j++];
}
}

Este algoritmo tiene complejidad O(n log n), que se obtiene resolviendo la ecuacin de
recurrencias T(n) = k n + 2 T(n/2). La solucin a la misma se puede comprobar gracias a la
tecnologas del sitio WolframAlpha

MERGE SORT
How Merge sort works:
This algorithm uses an array breaking technique. It breaks the array into half and gets two
arrays, sort those halves and than break them in to their halves and sort them, it continues this
process till there does not remain a one element in each divided array. After that it merges
these arrays with same order in which it broke the array. For this purpose merge sort uses a
recursive functions. Every time when function is called you have to send start, mid and end of
array.
Complexity of Merge Sort Algorithm:
This algorithm takes n log n time in its worst and average case. So we can say that its
complexity is BIG O of n log n.
.
To demonstrate this make a window form based application. Drag one button and one list box
on the form. Load an integer array in the list box and than press button to sort.
Now write the following code on Button Click event:
C#
private void btn_Sort_Click(object sender, EventArgs e)
{
MergeSort(0,4);
listBox_elements.Items.Clear();
for (int x = 0; x < arr.Length; x++)
listBox_elements.Items.Insert(x, arr.GetValue(x));
}
VB
Private Sub btn_Sort_Click(ByVal sender As Object, ByVal e As EventArgs)
MergeSort(0,4);
listBox_elements.Items.Clear()
For x As Integer = 0 To arr.Length - 1
listBox_elements.Items.Insert(x, arr.GetValue(x))
Next
End Sub
This is a simple code to call Merge Sort () Function. After sorting, this code will load the sorted
array in list box.
Now write the following code in Merge Sort () Function:
C#
private void MergeSort(int left,int right)
{
int mid = (left + right) / 2;
if (left < right) {
MergeSort(left, mid);
MergeSort(mid + 1, right);
merge(left, mid, right);
}
}
VB
Private Sub MergeSort(ByVal left As Integer, ByVal right As Integer)
Dim mid As Integer = (left + right) / 2
If left < right Then
MergeSort(left, mid)
MergeSort(mid + 1, right)
merge(left, mid, right)

End If
End Sub
C#
private void merge(int left,int mid,int right)
{
int y = 0, z = 0;
int leftno = mid - left + 1;
int rightno = right - mid;
int[] obj1 = new int[leftno];
int[]obj2 = new int[rightno];

for (y = 0; y < leftno; y++)
{
obj1.SetValue(arr.GetValue(left + y),y);
}
for (z = 0; z < rightno; z++)
{
obj2.SetValue(arr.GetValue(mid + z + 1),z);
}
y = 0;
z = 0;

for (int i = left; i <= right; i++)
{
if ((y < leftno) && (z < rightno))
{
if ((int)obj1.GetValue(y) <= (int)obj2.GetValue(z))
{
arr.SetValue(obj1.GetValue(y),i);
y++;
}
else
{
arr.SetValue(obj2.GetValue(z), i);
z++;
}
}
else if ((y < leftno) && (z >= rightno))
{
arr.SetValue(obj1.GetValue(y), i);
y++;
}
else if ((y >= leftno) && (z < rightno))
{
arr.SetValue(obj2.GetValue(z), i);
z++;
}

}
}
VB
Private Sub merge(ByVal left As Integer, ByVal mid As Integer, ByVal right As Integer)
Dim y As Integer = 0, z As Integer = 0
Dim leftno As Integer = mid - left + 1
Dim rightno As Integer = right - mid
Dim obj1 As Integer() = New Integer(leftno - 1) {}
Dim obj2 As Integer() = New Integer(rightno - 1) {}

For y = 0 To leftno - 1
obj1.SetValue(arr.GetValue(left + y), y)
Next
For z = 0 To rightno - 1
obj2.SetValue(arr.GetValue(mid + z + 1), z)
Next
y = 0
z = 0

For i As Integer = left To right
If (y < leftno) AndAlso (z < rightno) Then
If CInt(obj1.GetValue(y)) <= CInt(obj2.GetValue(z)) Then
arr.SetValue(obj1.GetValue(y), i)
y += 1
Else
arr.SetValue(obj2.GetValue(z), i)
z += 1
End If
ElseIf (y < leftno) AndAlso (z >= rightno) Then
arr.SetValue(obj1.GetValue(y), i)
y += 1
ElseIf (y >= leftno) AndAlso (z < rightno) Then
arr.SetValue(obj2.GetValue(z), i)
z += 1

End If
Next
End Sub
This is simple code to sort.
Now write the following code on FORM LOAD event:
C#
private void Form1_Load(object sender, EventArgs e)
{
arr.SetValue(8, 0);
arr.SetValue(9,1);
arr.SetValue(2, 2);
arr.SetValue(4, 3);
arr.SetValue(7, 4);
for (int i = 0; i < arr.Length; i++)
listBox_elements.Items.Insert(i, arr.GetValue(i));
this.Text = "DEVASP MERGE SORT APPLICATION";

}
VB
Private Sub Form1_Load(ByVal sender As Object, ByVal e As EventArgs)
Me.Text = "DEVASP MERGE SORT APPLICATION"
arr.SetValue(8, 0)
arr.SetValue(9, 1)
arr.SetValue(2, 2)
arr.SetValue(4, 3)
arr.SetValue(7, 4)
For i As Integer = 0 To arr.Length - 1
listBox_elements.Items.Insert(i, arr.GetValue(i))
Next
End Sub
This simple article tells some how to do sorting using MERGE sort in VB and C# .net 2.0.










Usando el Cdigo
Para llevar a cabo la combinacin de clase en VB.NET no es una tarea bastante fcil, pero ...
si usted tiene el concepto correcto, entonces no ser tan difcil. A continuacin se muestra
la funcin de combinacin de clase escrita para ordenar una matriz de enteros. Aunque es
posible encontrar varias versiones diferentes y muchas variaciones para la aplicacin del
tipo de combinacin, esta funcin es nica y se hace a mano de una manera especial para
lograr en el lugar de clasificacin, lo que significa que la matriz original no clasificada ser
reemplazada por la secuencia ordenada resultante, As que no hay nueva matriz se forma
reduciendo as al mnimo el consumo de memoria, porque como hemos dicho
anteriormente, fusionar especie se utiliza para ordenar grandes cantidades de informacin
por lo que debemos tener cuidado con nuestras limitaciones de memoria. Supongamos
que tenemos una matriz de enteros de 32 bits (4 bytes) de longitud 180 millones . El
tamao de la matriz ser 703125KB o 686MB que es un espacio de memoria
considerable. Supongamos que nuestro algoritmo de clasificacin crea una matriz
ordenada en vez de reemplazar la existente, entonces el espacio consumido total sera
de 1.34GB de RAM, una enorme cobertura de los usuarios de computadoras personales!
Aqu est el pblico mtodo para llamar fusionar pasando especie en la matriz. Tenga en
cuenta que las matrices en Visual Basic. Son tipos de referencia, por
lo ByVal y ByRef ambos significan estos ltimos.
Contraer | Copiar cdigo
Public Sub (MergeSort ByVal ar () Como Entero )
DoMergeSort (ar, 0 , ar.Length - 1 )
End Sub
La implementacin de IN-PLACE merge sort:
Contraer | Copiar cdigo
Private Sub DoMergeSort ( ByVal ar () Como Entero , _
ByVal bajo Como Entero , ByVal alta Como Entero )

Si bajo> = Alta Entonces Return
Dim longitud Como Entero = alto - bajo + 1
Dim media Como Entero = Math.Floor ((bajo + alto) / 2 )
DoMergeSort (ar, bajo, medio)
DoMergeSort (ar, media + 1 , alto)
Dim temp (ar.Length - 1 ) Como Entero
Para i Como Entero = 0 A longitud - 1
temp (i) = ar (baja + i)
Siguiente
Dim m1 Como Entero = 0
Dim m2 Como Entero = media - baja + 1
para i Como Entero = 0 A longitud - 1
Si m2 <= alto - bajo Entonces
Si m1 <= media - baja Entonces
Si temp (m1)> temp (m2) Entonces
ar (i + bajo) = temp (m2)
m2 + = 1
Else
ar (i + bajo) = temp (m1)
m1 + = 1
End Si
Else
ar (i + bajo) = temp (m2)
m2 + = 1
End Si
Else
ar (i + bajo) = temp (m1)
m1 + = 1
Fin Si
Siguiente

End Sub

Public Shared Sub MergeSort(input As Integer(), left As Integer, right As
Integer)
If left < right Then
Dim middle As Integer = (left + right) \ 2

MergeSort(input, left, middle)
MergeSort(input, middle + 1, right)

'Merge
Dim leftArray As Integer() = New Integer(middle - left) {}
Dim rightArray As Integer() = New Integer(right - middle - 1)
{}

Array.Copy(input, left, leftArray, 0, middle - left + 1)
Array.Copy(input, middle + 1, rightArray, 0, right - middle)

Dim i As Integer = 0
Dim j As Integer = 0
For k As Integer = left To right
If i = leftArray.Length Then
input(k) = rightArray(j)
j += 1
ElseIf j = rightArray.Length Then
input(k) = leftArray(i)
i += 1
ElseIf leftArray(i) <= rightArray(j) Then
input(k) = leftArray(i)
i += 1
Else
input(k) = rightArray(j)
j += 1
End If
Next
End If
End Sub

You might also like