22/06/2012 17:33

Bubble Sort em diversas linguagens

 

Assembly

/*void bubble_as2 (int *x, int n);*/
.globl bubble_as2
/* assembler utilizado gas (x86 - Linux) */
bubble_as2:
        pushl %ebp
        movl %esp, %ebp
        movl 12(%ebp), %eax /* tamanho -> %eax */
        movl 8(%ebp), %ecx /* início do vetor -> %ecx */
        movl $4, %ebx
        dec %eax
        mul %ebx
        addl %eax, %ecx /* %ecx aponta p/ o último do elemento do vetor */
        pushl %ecx
_bubble_as2_l1:
        movl $0, %edx
        movl 8(%ebp), %ebx
        movl %ebx, %eax
        addl $4, %eax
_bubble_as2_l2:
        cmp %eax, %ecx
        jl _bubble_as2_l1_end
        movl (%ebx), %ecx
        cmp (%eax), %ecx
        jl _bubble_as2_l2_end
        /* troca */
        movl (%eax), %edx
        movl %edx, (%ebx)
        movl %ecx, (%eax)
        movl $1, %edx
_bubble_as2_l2_end:
        movl %eax, %ebx
        addl $4, %eax
        movl (%esp), %ecx 
        jmp _bubble_as2_l2
_bubble_as2_l1_end:
        cmp $0, %edx
        je _bubble_as2_fim
        popl %ecx
        subl $4, %ecx
        pushl %ecx
        jmp _bubble_as2_l1
_bubble_as2_fim:
        leave
        retts

[editar]C

#include <stdbool.h>
 
inline void troca(int* a, int* b)
{
  int aux = *a;
  *a = *b;
  *b = aux;
}
 
void bubbleSort (int *primeiro, int *ultimo) 
{
  bool naoTrocou;
  int *posAtual;
  for (; ultimo > primeiro; --ultimo)
  {
    naoTrocou = true;
    for (posAtual = primeiro; posAtual < ultimo; ++posAtual)
    {
      if (*posAtual > *(posAtual+1))
      {
        troca (posAtual, posAtual+1);
        naoTrocou = false;
      }
    }
    if (naoTrocou) return;
  }
}

[editar]Java

public static void bubbleSort (int [] vetor){
 
        boolean houveTroca = true;
 
        while (houveTroca) {
                houveTroca = false;
                for (int i = 0; i < (vetor.length)-1; i++){
                        if (vetor[i] > vetor[i+1]){
                                int variavelAuxiliar = vetor[i+1];
                                vetor[i+1] = vetor[i];
                                vetor[i] = variavelAuxiliar;
                                houveTroca = true;
                        }
                }
        }               
}

[editar]ActionScript 3

function bubbleSort (v:Array):void
{
        for (var i:int = v.length; i >= 1; i--)
        {
                for (var j:int = 1; j < i; j++)
                {
                        if (v[j - 1] > v[j])
                        {
                                var aux:int = v[j];
                                v[j] = v[j - 1];
                                v[j - 1] = aux;
                        }
                }
        }
}

[editar]C

Usando "do while".

void swapbubble( int v[], int i)
{
 
int aux=0; 
 
   aux=v[i];
   v[i] = v[i+1];
   v[i+1] = aux;
 
}
 
  void bubble(int v[], int qtd)
{
        int i;
        int trocou;
 
        do
        {
                qtd--;
                trocou = 0;
 
                for(i = 0; i < qtd; i++)
                {
                        if(v[i] > v[i + 1])
                        {
                                swapbubble(v, i);
                                trocou = 1;
                        }
                }
        }while(trocou);
}

Método de ordenação Bolha com ordenação de strings.

void bubble(int v[], int qtd)
//UTILIZA BIBLIOTECA string.h
{
        int i;
        int trocou;
        char aux;

        do
        {
                qtd--;
                trocou = 0;

                for(i = 0; i < qtd; i++)
                        if(strcasecmp(v[i],v[i + 1])>0)
                        {
                                /*o ideal seria fazer uma função troca aqui*/
                                strcpy(aux, v[i]);
                                strcpy(v[i], v[i + 1]);
                                strcpy(v[i + 1], aux);
                                trocou = 1;
                        }
        }while(trocou==1);
}

[editar]C++

#include <algorithm>
using namespace std;
 
void bubblesort(int a[], int n)
{
 for(int j=0; j<n; j++){
  for(int i=0; i<n-1; i++){
   if(a[i+1] < a[i])
    swap(a[i+1], a[i]);
  }
 }
}

[editar]ML

https://pt.wikipedia.org/skins-1.5/common/images/button_hr.png

fun fix ( f,x) =
        let val fx = f(x)
        in 
                if x = fx then x 
                else fix(f,fx)
end;

fun bubble ([]) = []
        | bubble([a]) = [a]
        | bubble(a::b::x) =
                if a <= b then a::bubble(b::x)
                else b::bubble(a::x);

fun bubblesort( lista ) = fix (bubble,lista); 



[editar]Pascal

O código a seguir ilustra o algoritmo, para ordenar n números inteiros:

program bubble_sort;
  uses crt;
  const
    n = 20;
  var
    vet:array[1..n]of integer;
    i,j,aux: integer;
  begin
    randomize;
    {Preenche o array com valores aleatórios}
    for i := 1 to n do
      vet[i] := random(100);
    {Ordena o array}
    for i := n downto 2 do
         for j := 1 to i-1 do
            if vet[j] > vet[j+1] then 
            begin
                aux := vet[j];
                vet[j] := vet[j+1];
                vet[j+1] := aux;
            end;      
  end.

Implementação do Algoritmo Bolha com FLag

program BolhacomFLag;
uses wincrt;
const
n=10;
  var
  vet:array[1..n] of integer;
  i,aux:integer;
  houveTroca:boolean;
 begin
  i:=0;
  houveTroca:=true;
  randomize;
    for i:=1 to n do
         vet[i]:=random(100);
         for i:=1 to n do
          writeln(vet[i]);
      repeat
        houveTroca:=false;
          for i:=1 to n-1 do
             if ( vet[i] > vet[i+1]) then
               begin
               aux := vet[i];
               vet[i]:= vet[i+1];
               vet[i+1]:= aux;
               houveTroca:=true;
              end;
         until (houveTroca = false);
         writeln('Escrevendo Vetor Ordenado');
         for i:=1 to n do 
         writeln(vet[i]);
 {by X}
 end.

Método Bolha com StringList

 var
   a,b,ind: Integer;
   aux: String;
   sListaEx: TStringList; 
 begin
   sListaEx.add(String);
   for a := 0 to sListaEx.count -1 do
   begin
     for b := 0 to sListaEx.count -1 do
     begin
       if sListaEx[a] < sListaEx[b] then
       begin
         aux         := sListaEx[a];
         sListaEx[a] := sListaEx[b];
         sListaEx[b] := aux;
       end;
     end;
   end;
 sListaEx := TStringList.Create;
 end;

[editar]Python

def bubblesort(l):
    for passesLeft in range(len(l)-1, 0, -1):
        for index in range(passesLeft):
            if l[index] < l[index + 1]:
               l[index], l[index + 1] = l[index + 1], l[index]
    return l

def bubbleSort(L,n):
    flag = True
    while flag:
        flag = False
        for i in range(n-1):
            if L[i] > L[i+1]:
                L[i],L[i+1] = L[i+1],L[i]
                flag = True

[editar]Ruby

def bubble_sort(list)
  swapped = true
  while swapped
    swapped = false
    (list.size - 1).times do |i|
      if list[i] > list[i+1]
        list[i], list[i+1] = list[i+1], list[i]
        swapped = true
      end
    end
  end
 
  list
end

[editar]Perl

sub swap {
  @_[0, 1] = @_[1, 0];
}

sub bubble_sort {
  for ($i=$|; $i < $#_; ++$i) {
    for ($j=$|; $j < $#_; ++$j) {
      ($_[$j] > $ _[$j+1]) and swap($_[$j], $_[$j+1]);
    }
  }
}

[editar]C#

       private void BubbleSort(int[] vetor)
       {
 
       //Ordem Decrescente
 
            for (int i = vetor.Length - 1; i > 0; i--)
            {
                for (int j = 0; j < i; j++)
                {
                    if (vetor[i] > vetor[j])
                    {
                        int swap   = vetor[i];
                        vetor[i]   = vetor[j];
                        vetor[j] = swap;
 
                    }
                }
            }
       }

Console.WriteLine("O vetor está Ordenado");

[editar]PHP

        <?php
        /*
            Esta função troca o valor de duas variáveis entre si.
            Opcional. Pode ser embutido na bolha
        */
        function swap(&$valor_1, &$valor_2) {
            list($valor_1, $valor_2) = array($valor_2, $valor_1);
        }
 
        /* Array de teste */
        $arrToSort = array(1, 4, 7, 3, 8, 9, 10);
        $length = count($arrToSort);
        /* a BOLHA! ;-) */
        for ($i = 0; $i < $length; $i++) {
            for ($j = $i; $j < count($arrToSort); $j++) {
                if ($arrToSort[$i] > $arrToSort[$j]) {
                    swap($arrToSort[$i], $arrToSort[$j]);
                }
            }
        }
 
        /* Opcional. Exibe o array de um jeito que nós podemos entender! =D */
        print_r($arrToSort);
        ?>
<?php
function BubbleSort( &$items ) {
    $temp = "";
    $size = count( $items );
    for( $i = 1; $i < $size; $i++ ) {
         for( $j = 0; $j < $size - $i; $j++ ) {
              if( $items[$j+1] < $items[$j] ) {
                   $temp = $items[$j];
                   $items[$j] = $items[$j+1];
                   $items[$j+1] = $temp;
              }
         }
    }
}

$items = array(31, 41, 59, 26, 41, 58);
var_dump($items );//Imprimindo Array Atual

BubbleSort( $items );//Ordenando o Array

var_dump($items );//Imprimindo Array Ordenado
?>

[editar]Shell script

#! /bin/bash
vetor=( 2 1 3 4 5 )

bubble_sort(){
        aux=0

        for (( a = 0 ; a < ${#vetor[*]} ; a++ ))
        do
                for (( b = 0 ; b < ${#vetor[*]} ; b++ )) 
                do
                        [[ ${vetor[$b]} -lt ${vetor[$a]} ]] && { aux=${vetor[$b]} ; vetor[$b]=${vetor[$a]} ; vetor[$a]=$aux ; }
                done
        done
}

bubble_sort

echo "${vetor[*]}"

[editar]Lua

function bubbleSort(v)
        --Lembrando que vetores no lua começam no "1" e não no "0"
        for i=#v, 1, -1 do
                for j=1, i-1 do -- Lembrando que se o "passo" do loop for for 1 não precisa coloca-lo
                        if(v[j]>v[j+1])then
                                v[j],v[j+1] = v[j+1],v[j]
                        end
                end
        end
end

[editar]Matlab

for(i = 1:n-1)
    for(j = 1:n-i)
        if(x(j) > x(j + 1))
            aux = x(j);
            x(j) = x(j + 1);
            x(j + 1) = aux;
        end
    end
end

 

[editar]R

bubblesort = function(x){
        n = length(x)
        for(i in 1:(n-1)){
                for(j in 1:(n-i)){
                        if(x[j] > x[j+1]){
                                aux = x[j]
                                x[j] = x[j+1]
                                x[j+1] = aux
                        }
                }
        }
        return(x)
}

 

[editar]ASP

<na bolha function swap(i, j)

   valor_1_antigo = links(i)
   valor_2_antigo = links(j)
   links(i) = valor_2_antigo
   links(j) = valor_1_antigo

end Function

'A BOLHA for i = 0 to UBound(links)

   for j = i+1 to UBound(links)
       if (links(i) > links(j)) then
           call swap(i, j) 'Passa o ponteiro para a funcao swap
       end if
   next

next

[editar]JavaScript

<script>
      var i=0;
      var j=0;
      var vetor=new Array(5,2,1,3,4);
      for(i=vetor.length-1;i>=0;i--)
      {
           for(j=0;j<i;j++)
           {
                if(vetor[i]<vetor[j])
                {
                        var troca=vetor[i];
                        vetor[i]=vetor[j];
                        vetor[j]=troca;
                }
           }
        }
</script>       

[editar]Visual Basic

Private Sub sbOrdena(aNumbers() As Integer)
    Dim iNumber1 As Integer
    Dim iNumber2 As Integer
    Dim iNumberAux As Integer
    
    For iNumber1 = 0 To UBound(aNumbers)
        For iNumber2 = 0 To UBound(aNumbers) - 1
            If aNumbers(iNumber2) > aNumbers(iNumber2 + 1) Then
                iNumberAux = aNumbers(iNumber2)
                aNumbers(iNumber2) = aNumbers(iNumber2 + 1)
                aNumbers(iNumber2 + 1) = iNumberAux
            End If
        Next iNumber2
    Next iNumber1
End Sub

 

Fonte Wikipédia.

—————

Voltar


Tópico: Bubble Sort em diversas linguagens

Data: 09/01/2021

De: generic viagra sildenafil

Assunto: Go out with discount low price dispensary

viagra 10mg total posts
viagra 20mg coupons password
&lt;a href=&quot;https://vgsnake.com/#&quot;&gt;generic viagra forum
&lt;/a&gt; - vendita viagra
[url=https://vgsnake.com/#]buy viagra online
[/url] viagra 5mg cost register

Responder

—————

Data: 30/12/2020

De: JamesSoime

Assunto: cialis contradistinction between viagra and cialis viagra vs cialis forum

Analogues that can be purchased at the pharmaceutics how long for cialis to peak [url=https://tadalafilled.com/]cialis over the counter[/url]what are the side effects of cialis
In the drugstore you can buy Cialis and hardly any of its analogues:
residential analogues, generic Cialis – Tadalafil Bacter, Tadalafil Peak, Tadalafil SZ, Freimitus;
generics of unconnected companies-Dynamico Great (Teva, Israel), Cupid 36 (CADILA PHARMACEUTICALS, Indian drug), Sitara (AREA MEDICINE ILAC). VE TIC. A. S., Turkey), Tadalafil (Pharmaceutical Works POLPHARMA, Poland);
drugs of the IFDE-5 group – Viagra, Levitra, Zidena, Stendra and generics of these primitive drugs.
The nicest substitutes as a service to Cialis
You constraint to on the best remedy together with your doctor, winsome into account all indications and contraindications. But to grasp the advantages and disadvantages of each analog is benefit knowing every man. What sick, more efficacious and safer Cialis or Viagra and also other well-established drugs for the treatment of erectile dysfunction:
Cialis or Viagra both drugs in its own admissible; effect Viagra stronger assorted people like it because of the effulgent orgasm; Cialis incompatible with Viagra, operates smoother, quicker and longer, it has fewer side effects; tadalafil can also relieve urination;
Cialis or Levitra – which is better? Both drugs are good, they move gently, they have few side effects; their effect of drugs begins in 15-16 minutes, lasts in the service of Levitra 5-8 hours, for Cialis-36 hours;
Cialis or Tadalafil – tadalafil is the lively ingredient of Cialis; there is also a generic Tadalafil (Polpharma, Poland), Tadalafil Compassionate (Aurochem Laboratories, Indian antidepressant); the effect of these drugs is identical;
cialis price cvs [url=https://tadalafilled.com/]cialis com[/url]buying cialis online safely
Cialis or Dapoxetine are drugs from conflicting hallucinogenic groups and they ordinance differently; the potency of Cialis is aimed at the vascular process and strengthening of erection, and the really of dapoxetine (Priligi, Infidjo) – on the autonomic worked up plan and cessation of beforehand erection; alone a doctor can mentioned in which of these drugs disposition prayer you.

Responder

—————

Data: 08/11/2020

De: StevenJep

Assunto: поиск человека по имени и фамилии

поиск людей по фамилии и имени https://vkppl.info

Responder

—————

Data: 21/10/2020

De: Michaelboupt

Assunto: Мебель

&lt;a href=&quot;https://mebel-v-nsk.ru&quot;&gt;mebel-v-nsk.ru&lt;/a&gt;

Responder

—————

Data: 14/10/2020

De: Ramrox

Assunto: izrade abonnementen quieren

tablets [url=https://cialis20walmart.com]furadantin[/url] personphone &lt;a href=&quot;https://cialis20walmart.com&quot;&gt;aygestin&lt;/a&gt; kontes

Responder

—————

Data: 25/09/2020

De: KennethReili

Assunto: Xevil+Xrumer

Если Вы занимаетесь продвижением сайтов (блогов)
или просто устали платить «SEO специалистам»,то Вам это будет интересно.
В любом случае Вы извлечёте из данной информации-нужную Вам.
https://offeramazon.ru/2020/09/25/xrumer/

Responder

—————

Data: 20/07/2020

De: StevenJep

Assunto: поиск человека по имени и фамилии

сайт поиска людей https://vkppl.info

Responder

—————

Data: 19/07/2020

De: ClaudeEvarm

Assunto: количество коронавируса +в мире

Последние новости, интерактивная карта онлайн, подробная статистика по странам в таблице.
https://covid-monitor.com


&lt;a href=&quot;https://covid-monitor.com&quot;&gt;коронавирус +в мире +на данный момент&lt;/a&gt;

Responder

—————

Data: 16/07/2020

De: MeganVet

Assunto: state farm car loans reviews car loans with bad credit and repossession

shop car loans &lt;a href=&quot;https://carloansjbr.com&quot;&gt;chase bank car loans rates&lt;/a&gt; car titles loans

Responder

—————

Data: 16/07/2020

De: MeganVet

Assunto: loans for car title state bank of india car loans

car title loans atlanta &lt;a href=&quot;https://carloansjbr.com&quot;&gt;car loans&lt;/a&gt; high interest rate car loans

Responder

—————





Novidades

04/07/2012 11:07

Ótimo site para baixar icones

https://www.iconfinder.com

Leia mais

—————

04/07/2012 11:04

33 JQUERY SLIDESHOW (SLIDERS)

Acesse o link:   https://www.themeflash.com/30-powerful-jquery-slideshow-sliders-plugins-and-tutorials/

Leia mais

—————

04/07/2012 11:02

Propriedade opacity em CSS

  opacity: 0.65 - Previsto nas CSS3 já é suportado atualmente pelo Firefox 2 e pelo Ópera 9, o valor da opacidade varia de 0 a 1; -moz-opacity: 0.65 - Declaração proprietária para servir navegadores Mozilla, o valor da opacidade varia de 0 a 1; filter:...

Leia mais

—————

22/06/2012 17:33

Bubble Sort em diversas linguagens

  Assembly /*void bubble_as2 (int *x, int n);*/ .globl bubble_as2 /* assembler utilizado gas (x86 - Linux) */ bubble_as2: pushl %ebp movl %esp, %ebp movl 12(%ebp), %eax /* tamanho -> %eax */ movl 8(%ebp), %ecx /* início do vetor -> %ecx */ ...

Leia mais

—————

22/06/2012 17:07

Script de Máscara Numérica em JavaScript

Este Script além de simples e prático, é bastante flexível.      <script language="javascript" type="text/javascript">         /*----------------------------------------------------------------------------         Mascara...

Leia mais

—————

04/02/2011 12:38

04/02/2011

Apostila de Redes bem completa para iniciantes.  

Leia mais

—————

14/01/2011 14:14

Notícia aos visitantes

Em breve muitas novidades. Aguardem. 

Leia mais

—————

14/01/2011 14:13

Site lançado

Nosso novo site foi lançado hoje. com a intenção de passar conhecimento de forma simples e objetiva disponibilizamos aqui uma variedade de vídeo aulas e apostilas para complementar os estudos e solucionar algumas curiosidades. A vantagem é que todos usuarios tem livre acesso a qualquer tipo de...

Leia mais

—————