Ordenar array em C , JAVASCRIPT e JAVA
- #JavaScript
- #Java
Em C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <math.h>
main()
{
int size=10;
float vetor[size];
srand(time(NULL));
for(int z=0 ;z<size;z++){ // popular o array
vetor[z]=floor(rand()%10000);
}
for(int z=0;z<size;z++){
printf("%.2f ",vetor[z]);
}
for(int z=0;z<size;z++){ // ordenar o array
for(int y=z+1;y<size;y++){
if(vetor[z] > vetor[y]){
float aux=vetor[z];
vetor[z]=vetor[y];
vetor[y]=aux;
}
}
}
printf("\n\n");
for(int z=0;z<size;z++){
printf("%.2f ",vetor[z]);
}
system("pause");
}
Array gerado
5678.00 8126.00 8312.00 1947.00 6639.00 398.00 4910.00 2056.00 4206.00 317.00
Array ordenado
317.00 398.00 1947.00 2056.00 4206.00 4910.00 5678.00 6639.00 8126.00 8312.00
Em JAVASCRIPT
const size=10;
const array=[];
for(let i=0;i<size;i++){ // popular o array
array.push(Math.floor(Math.random()*10000));
}
console.log(array);
array.sort((a,b) => a-b); // ordenar o array
console.log(array);
Array gerado
[ 4995,184,6596,2911,2767,447,4570,5794,7815,6726]
Array ordenado
[ 184,447,2767,2911,4570,4995,5794,6596,6726,7815]
Em JAVA
package orderArray;
import java.util.Arrays;
import java.util.Random;
public class OrderArray {
public static void main(String[] args) {
final int size=10;
int[] array = new int[size];
Random geradorAleatorio = new Random();
for(int i=0;i<size;i++) { // popular o array
array[i] = geradorAleatorio.nextInt(10000);
}
System.out.println(Arrays.toString(array));
Arrays.sort(array);// ordenar array
System.out.println();
System.out.println(Arrays.toString(array));
}
}
Array gerado
[2126, 5857, 514, 3205, 881, 7780, 2328, 361, 4678, 5238]
Array ordenado
[361, 514, 881, 2126, 2328, 3205, 4678, 5238, 5857, 7780]