algorithm - Why JavaScript selection sort hangs -
i have following code:
var longlorem = "..."; // here string, > 1 000 000 length var buffersize = 1000000; var lorem = longlorem.substring(0, buffersize - 1).split(''); var swap; var i, j; for(i=0;i<buffersize;i++){ for(j=i+1;j<buffersize;j++){ if(lorem[i] > lorem[j]){ swap = lorem[i]; lorem[i] = lorem[j]; lorem[j] = swap; } } }
why hangs under chrome? how speed javascript or not possible dom , ui, etc.?
with buffersize=100 000
completes in 2m 35s.
the following c program completes in >17m
#include <stdio.h> #define buffersize 1000000 int main( int argc, char *argv[] ) { int i,j; char swap; file *loremfile = fopen("lorem.txt", "r"); char buff[buffersize]; fgets(buff, buffersize, (file*)loremfile); fclose(loremfile); //printf("'%s'\n-----end--------\n", buff ); for(i=0; i<buffersize-1;i++) { for(j=i+1;j<buffersize-1;j++) { if((int)buff[i] > (int) buff[j]) { swap = (char)buff[i]; //printf("%c %c\n", buff[i], buff[j]); buff[i] =(char) buff[j]; buff[j] = swap; } } } //buff[buffersize-1] = '\0'; // for(i=0;i<buffersize;i++){ // printf("%c", buff[i]); // } printf("'%s'\n-----end--------\n", buff); printf("exit\n"); return 0; }
and c# code completes 10m:
using system; namespace mysort { public class { public static void main() { int buffersize = 1000000; string loremfile = system.io.file.readalltext("lorem.txt"); var chars = loremfile.tochararray(0, buffersize); for(int = 0; i<buffersize; i++) { for(int j=i+1; j<buffersize; j++) { if(chars[i] > chars[j]) { char swap = chars[i]; chars[i] = chars[j]; chars[j] = swap; } } } console.write("'"); console.write(chars); console.write("'\n"); } } }
i believe chrome has tendency of hanging during long operations, , crash. i've done things in chrome , firefox, , chrome crash tab firefox take forever well, wouldn't crash. keep getting continue/stop script popup though on firefox.
if you're saying it's taking around 20 minutes complete in c
imagine web browser take long (if not longer), , in cases browsers attempt kill script.
Comments
Post a Comment